passing lambda to void specified template fails

  • A+

i simplified the problem as much as i could so here is the function in question:

class Test { public:     template<class T>     void ExecuteFunction(std::function<void(T)> f)     {     } }; 

if i call the function with int-typing everything works fine, however, if i call it with a void-typed lambda it doesn't compile anymore.

Test test;  test.ExecuteFunction<void>(    // doesn't compile     [](void)->void {     int i = 5; });  test.ExecuteFunction<int>(    // this compiles     [](int)->void {     int i = 5; }); 

Compiler errors:

Error   C2672   'Test::ExecuteFunction': no matching overloaded function found   Error   C2770   invalid explicit template argument(s) for 'void Test::ExecuteFunction(std::function<void(P)>)'   Error (active)      no instance of function template "Test::ExecuteFunction" matches the argument list 

is there a way around this? how would someone specify the template so that both calls work?


Is too late to play?

I propose another solution based on a custom type trait (with a specialization for void) that, given a T type, define the correct std::function type; i mean

template <typename T> struct getFuncType  { using type = std::function<void(T)>; };  template <> struct getFuncType<void>  { using type = std::function<void()>; }; 

This way your ExecuteFunction() simply become

template <typename T> void ExecuteFunction (typename getFuncType<T>::type f) { } 

If you want simplify a little the use of getFuncType, you can add a using helper to extract the type

template <typename T> using getFuncType_t = typename getFuncType<T>::type; 

so the ExecuteFunction() can be simplified as follows

template <typename T> void ExecuteFunction (getFuncType_t<T> f) { } 


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