C++ Functions with lambdas as arguments -
i have overload function, following signatures:
void foo(const std::function<void(int )> &func); void foo(const std::function<void(int, int)> &func);
and when want use foo() lambdas, i'll have this:
foo((std::function<void(int )>) [] (int ) { /* */ }); foo((std::function<void(int, int)>) [] (int i, int j) { /* */ });
both of not user-friendly. it'd lot easier use function without having add casting "(std::function<...>)" before lambdas - this:
foo([] (int ) { /* */ }); // executes 1st foo() foo([] (int i, int j) { /* */ }); // executes 2nd foo()
so, need overload, accept lambda argument, , automatically casts lambda 1 of above signatures. how can done? or, possible in first place?
template <typename function> void foo(function function) { // insert code here: should // - check signature of 'function'; , // - call 'foo()' corresponding signature }
please help.
ps. i'm using vs2010.
if lambda not capture variables—that is, begins []
—then convertible function pointer, , can declare foo
so:
void foo(void(*func)(int)); void foo(void(*func)(int, int));
if want keep std::function
versions, can have these versions forward one. if don’t want implement them separately, think variadic template nicely:
template<class... args> void foo(void(*func)(args...)) { return std::function<void(args...)>(func); }
if lambdas capture variables, they’re not convertible function pointers, , you’ll need wrap them in std::function
yourself.
Comments
Post a Comment