I would like to know what is the correct type definition for the lambda presented below, so that the following code will compile using a conformant c++11 compiler:
#include <cstdio>
#include <string>
template<class Func>
class foo
{
public:
foo(Func func)
: fum(func){}
Func fum;
};
int main()
{
foo<???> fi([](int i) -> bool { printf("%d",i); return true; });
fi.fum(2);
return 0;
}
I guess another way it could be done is like so:
template<typename Func>
foo<Func> make_foo(Func f)
{
return foo<Func>(f);
}
int main()
{
auto fi = make([](int i) -> bool { printf("%d",i); return true; });
fi.fum(2);
return 0;
}
It's
auto
+decltype
:Every single lambda has a different, unique, unnamed type. You, as a coder, just can not name it.
However, in your case, since the lambda doesn't capture anything (empty
[]
), it is implicitly convertible to a pointer-to-function, so this would do:It's
std::function<bool(int)>
. Or possibly justbool(*)(int)
if you prefer, since the lambda doesn't capture.(The raw function pointer might be a bit more efficient, since
std::function
does (at least in some cases) require dynamic allocation for some type erasure magic.)