You can do this if add return functor , i.e. an object that implements operator() . You can write a boilerplate version that allows the compiler to infer the type. Try it here .
template <class T> struct adder { T val; adder(T a) : val(a) {} template <class T2> auto operator()(T2 a) -> adder<decltype(val + a)> { return val + a; } operator T() const { return val; } }; template <class T> adder<T> add(T a) { return a; }
Example
In this example, T will eventually resolve double :
std::cout << add(1)(2.5)(3.1f)(4) << std::endl;
Here is another example where T will be resolved double :
std::cout << add(1)(2.5f)(3.1)(4) << std::endl;
Explicit constructor
If you want the adder constructor to be explicit , you also need to slightly modify the return statements.
template <class T> struct adder { T val; explicit adder(T a) : val(a) {} template <class T2> auto operator()(T2 a) -> adder<decltype(val + a)> { return adder<decltype(val + a)>(val + a); } operator T() const { return val; } }; template <class T> adder<T> add(T a) { return adder<T>(a); }
source share