C++11 lambda in decltype

2020-02-08 10:23发布

For the following code:

auto F(int count) -> decltype([](int m) { return 0; }) 
{                                                               
    return [](int m) { return 0; };                                  
}

g++ 4.5 gives the errors:

test1.cpp:1:32: error: expected primary-expression before 'int'
test1.cpp:1:32: error: expected ')' before 'int'

What is the problem? What is the correct way to return a lambda from a function?

3条回答
姐就是有狂的资本
2楼-- · 2020-02-08 10:33

You cannot use a lambda expression except by actually creating that object- that makes it impossible to pass to type deduction like decltype.

Ironically, of course, the lambda return rules make it so that you CAN return lambdas from lambdas, as there are some situations in which the return type doesn't have to be specified.

You only have two choices- return a polymorphic container such as std::function, or make F itself an actual lambda.

auto F = [](int count) { return [](int m) { return 0; }; };
查看更多
Rolldiameter
3楼-- · 2020-02-08 10:40

With C++14, you can now simply omit the return type:

auto F(int count)
{
    return [](int m) { return 0; };
}
查看更多
一夜七次
4楼-- · 2020-02-08 10:50

something like this fits your needs?

#include <functional>

std::function<int(int)> F(int count)
{                                                               
    return [](int m) { return 0; };                                  
}
查看更多
登录 后发表回答