【问题标题】:G++ Error Message "Operands to ?: have different types" but I Have Two Times the Same TypeG ++错误消息“操作数?:具有不同的类型”但我有两次相同的类型
【发布时间】:2017-05-24 19:21:43
【问题描述】:

为什么下面的代码不能编译? 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 有自己独立的实现,因此它们被视为独立的类型,即使它们碰巧具有相同的签名。
  • ....听起来很合理,但错误消息不应该反映这一点吗?目前它说,对于某些“A”,A 与 A 不同。

标签: c++ gcc c++14


【解决方案1】:

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

【讨论】:

  • ....听起来很合理,但错误消息不应该反映这一点吗?目前它说,对于某些“A”,A 与 A 不同
  • @DCTLib 是的,如果您不知道问题所在,则该消息不是很有帮助。你用的是什么版本的g++? IIRC 我已经看到关于 lambdas 的 g++ 消息,每个 lambdas 都有一些神秘的名称。
  • 我使用“G++ 6.3.0 20170406” - Ubuntu 17.04 的当前版本
  • IMO 不太可能得到一个可读的 lambdas 名称,毕竟它们是匿名的。
猜你喜欢
  • 2012-06-03
  • 2019-12-18
  • 2019-04-15
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多