In C++11, is there a way to template a lambda function? Or is it inherently too specific to be templated?
I understand that I can define a classic templated class/fu
Here is one solution that involves wrapping the lamba in a structure:
template
struct LamT
{
static void Go()
{
auto lam = []()
{
T var;
std::cout << "lam, type = " << typeid(var).name() << std::endl;
};
lam();
}
};
To use do:
LamT::Go();
LamT::Go();
#This prints
lam, type = i
lam, type = c
The main issue with this (besides the extra typing) you cannot embed this structure definition inside another method or you get (gcc 4.9)
error: a template declaration cannot appear at block scope
I also tried doing this:
template using LamdaT = decltype(
[](void)
{
std::cout << "LambT type = " << typeid(T).name() << std::endl;
});
With the hope that I could use it like this:
LamdaT();
LamdaT();
But I get the compiler error:
error: lambda-expression in unevaluated context
So this doesn't work ... but even if it did compile it would be of limited use because we would still have to put the "using LamdaT" at file scope (because it is a template) which sort of defeats the purpose of lambdas.