gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:25:25 25 4
gpt4 key购买 nike

为什么下面的代码不能编译? 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)”。

最佳答案

消息是正确的。每个 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);
}

关于c++ - G++ 错误消息 "Operands to ?: have different types"但我有两次相同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44166886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com