You can never know the type of lambda function because what logically happens is the compiler generates a (local) class with the function call operator overloaded and a lexical closure is represented by data members of that (local) class. This is what logically happens for a lambda function such as:
auto foo = [](int x, int y) { return x + y; };
The compiler logically does this:
struct CompilerGeneratedName { void operator()(int x, int y) const { return x + y; } };
CompilerGeneratedName foo;
Since the compiler generates a (local) class, it generates a name and therefore you can never explicitly write the type, you can only deduce the type from either type deductions of template function arguments or using auto/decltype.
Also C++0x closures are statically allocated so you couldn't safely return a raw C++0x closure anyway.
Still there are few ways you can achieve this, the first is more flexible and supports lambda functions which capture lexical scopes. Use std::function, if you have a lambda function which isn't capturing anything from outer scope then you can use function pointers but this conversion is more for working with legacy code than anything.
So basically what you want is this:
std::function< int (int) > foo(int x)
{
return [x](int y)->int{return x * y;};
}
The reason why I kept on saying logically, is because this is how boost::lambda kind of works originally (even though C++03 does not allow local classes to used in template function arguments) and where the idea of adding lambda functions originate from but since this is a language feature now compiler vendors could implement it in different and more efficient ways like when capturing all of the environment by reference the compiler can just pass a pointer to the call stack instead of the logical way while still maintaining the logical view.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…