How can a variadic template be used to generate a left-associative expression (aka left fold) in c++11?
Parameter packs on the left are problematic. Better reimplement it as a parameter pack on the right:
template<typename T, binary_op<T> Operation>
inline T fold_left(const T& t) { return t; }
template<typename T, binary_op<T> Operation, typename ... Rest>
inline T fold_left(const T& a, const T& b, Rest... rest) {
return fold_left<T, Operation>(Operation(a,b), rest...);
}
Michael answered your 1st Q. The 2nd may have different answers. My prefered way is to define your operations as functors with template members:
#include <type_traits>
struct homogene_add{
template<typename T>
T operator()(T const& lhs, T const& rhs){/*...*/}
};
struct mixed_add{
template<typename L, typename R>
std::common_type<L,R>::type
operator()(L const& lhs, R const& rhs){/*...*/}
};
template<typename binary_op, typename ... Args>
std::common_type<Args...>::type
fold_right(const Args&... args);
template<typename binary_op, typename First, typename ... Args>
std::common_type<First, Args...>::type
fold_right(const First& init, const Args&... args) {
binary_op op;
return op(init, fold_right<binary_op>(args...));
};
template<typename binary_op, typename First>
const First& fold_right(const First& init) {
return init;
};
CV qualification and valueness correctness, I leave to the OP.