为什么下面的代码不能编译?g++ 输出错误消息:
\n\ntest.cpp: In function \xe2\x80\x98void test(bool)\xe2\x80\x99:\ntest.cpp:11:15: error: operands to ?: have different types \xe2\x80\x98test(bool)::<lambda(int)>\xe2\x80\x99 and \xe2\x80\x98test(bool)::<lambda(int)>\xe2\x80\x99\n yadda(flag?x:y);\n ~~~~^~~~\nRun Code Online (Sandbox Code Playgroud)\n\n这对我来说没有什么意义,因为错误消息中给出的两种类型似乎是相同的。我正在使用以下代码:
\n\n#include <functional>\n\nvoid yadda(std::function<int(int)> zeptok) {\n zeptok(123);\n}\n\nvoid test(bool flag) {\n int a = 33;\n auto x = [&a](int size){ return size*3; };\n auto y = [&a](int size){ return size*2; };\n yadda(flag?x:y);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我使用“g++ -c test.cpp -std=c++14”进行编译,我的GCC版本是“6.3.0 20170406 (Ubuntu 6.3.0-12ubuntu2)”。
\n小智 5
该消息是正确的。每个 lambda 都是不同的类型。将它们视为都定义的两个不同的结构operator()。使用 astd::function代替auto:
void test(bool flag) {
int a = 33;
std::function<int (int)> x = [&a](int size){ return size*3; };
std::function<int (int)> y = [&a](int size){ return size*2; };
yadda(flag?x:y);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1719 次 |
| 最近记录: |