首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >G++错误消息"Operands to ?:have different types“,但我有两次相同的类型

G++错误消息"Operands to ?:have different types“,但我有两次相同的类型
EN

Stack Overflow用户
提问于 2017-05-25 03:21:44
回答 1查看 1.5K关注 0票数 1

为什么下面的代码不能编译?g++输出错误消息:

代码语言:javascript
复制
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);
           ~~~~^~~~

这对我来说意义不大,因为错误消息中给出的两种类型似乎是相同的。我使用了以下代码:

代码语言:javascript
复制
#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)”。

EN

回答 1

Stack Overflow用户

发布于 2017-05-25 03:30:54

消息是正确的。每个lambda都是一种不同的类型。可以将它们看作两个不同的结构,它们都定义了operator()。使用std::function而不是auto

代码语言:javascript
复制
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);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44166886

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档