C++ Template deduction from lambda

  • A+

I have a function which takes two std::function as arguments. The parameter of the second function has the same type as the result of the first.

I wrote a function template like this:

template<typename ResultType> void examplFunction(std::function<ResultType()> func, std::function<void(ResultType)> func2) {   auto x = func();   func2(x); } 

I can call it with:

void f() {   examplFunction<int>([]() { return 1; },   //                       [](int v) { std::cout << "result is " << v << std::endl; }); } 

Is there any way to to get rid of the <int> at examplFunction<int> and let the compiler deduce the type of ResultType?


Do you actually need std::function in there? std::function is useful when you need type erasure. With templates, you can usually skip it altogether:

template<class F1, class F2> void examplFunction(F1 func, F2 func2, decltype(func2(func()))* sfinae = nullptr) {   auto x = func();   func2(x); } 

The sfinae parameter makes sure the function can only be called with functions such that func2 can be called with the result of func.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: