为什么下面的代码不能编译?g++输出错误消息:
test.cpp: In function ‘void test(bool)’:
test.cpp:11:15: error: operands to ?: have different types ‘test(bool)::<lambda(int)>’ and ‘test(bool)::<lambda(int)>’
yadda(flag?x:y);
~~~~^~~~这对我来说意义不大,因为错误消息中给出的两种类型似乎是相同的。我使用了以下代码:
#include <functional>
void yadda(std::function<int(int)> zeptok) {
zeptok(123);
}
void test(bool flag) {
int a = 33;
auto x = [&a](int size){ return size*3; };
auto y = [&a](int size){ return size*2; };
yadda(flag?x:y);
}我用"g++ -c test.cpp -std=c++14“编译,我的GCC版本是"6.3.0 20170406 (Ubuntu 6.3.0-12ubuntu2)”。
发布于 2017-05-25 03:30:54
消息是正确的。每个lambda都是一种不同的类型。可以将它们看作两个不同的结构,它们都定义了operator()。使用std::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);
}https://stackoverflow.com/questions/44166886
复制相似问题