相关疑难解决方法(0)

一个积极的lambda:'+ [] {}' - 这是什么巫术?

在Stack Overflow问题中,在C++ 11中不允许重新定义lambda,为什么?,给出了一个不编译的小程序:

int main() {
    auto test = []{};
    test = []{};
}
Run Code Online (Sandbox Code Playgroud)

问题得到了回答,一切似乎都很好.然后是Johannes Schaub并做了一个有趣的观察:

如果你+在第一个lambda之前放置一个,它会神奇地开始工作.

所以我很好奇:为什么以下工作呢?

int main() {
    auto test = +[]{}; // Note the unary operator + before the lambda
    test = []{};
}
Run Code Online (Sandbox Code Playgroud)

它与GCC 4.7+和Clang 3.2+都很好.代码标准是否符合要求?

c++ lambda operator-overloading language-lawyer c++11

255
推荐指数
1
解决办法
3万
查看次数

将捕获lambda作为函数指针传递

是否可以将lambda函数作为函数指针传递?如果是这样,我必须做错了,因为我收到编译错误.

请考虑以下示例

using DecisionFn = bool(*)();

class Decide
{
public:
    Decide(DecisionFn dec) : _dec{dec} {}
private:
    DecisionFn _dec;
};

int main()
{
    int x = 5;
    Decide greaterThanThree{ [x](){ return x > 3; } };
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,我得到以下编译错误:

In function 'int main()':
17:31: error: the value of 'x' is not usable in a constant expression
16:9:  note: 'int x' is not const
17:53: error: no matching function for call to 'Decide::Decide(<brace-enclosed initializer list>)'
17:53: note: candidates are: …
Run Code Online (Sandbox Code Playgroud)

c++ lambda function-pointers c++11

186
推荐指数
4
解决办法
12万
查看次数