I am trying to compile the following code
#include <iostream>
#include <string>
struct Bar{ };
struct Foo {
template<class T>
void setCallback(std::function<void(T)> f) {
}
};
int main() {
Foo foo;
foo.setCallback<Bar>([](Bar v) { }); // <--- compilation ok
foo.setCallback([](Bar v) { }); // <--- compilation error. How to fix?
}
But the result of the compilation is fail:
main.cpp:16:9: error: no matching member function for call to 'setCallback'
foo.setCallback([](Bar v) { }); // <--- compilation error
~~~~^~~~~~~~~~~
main.cpp:9:10: note: candidate template ignored: could not match 'std::function<void (T)>' against '(lambda at main.cpp:16:21)'
void setCallback(std::function<void(T)> f) {
^
1 error generated.
How to tell to the compiler to deduct argument type of the lambda from lambda passing to the function?
UPDATE: I found solution for my problem:
template<typename F, typename R, typename E>
static E ArgHelper(R(F::*)(E) const);
template<typename F, typename R, typename E>
static E ArgHelper(R(F::*)(E));
struct Foo {
template<class T>
void setFunction(T func) {
using Arg = decltype(ArgHelper(&T::operator()) );
//use Arg
}
};
// use:
foo.setFunction([](Bar b){
//...
});