【问题标题】:different types in operator ? with no-capture, same signature, lambda运算符中的不同类型?无捕获,相同签名,lambda
【发布时间】:2020-09-04 12:26:34
【问题描述】:

根据 c++ 标准,lambda 函数具有唯一的类型,因此通常两个 lambda 不能与 ? 运算符一起使用。但是,正如this question 中所讨论的,没有捕获的 lambda 可以转换为函数指针。因此,以下代码可以正确编译:

int main()
{
    bool x = true;
    auto a_lambda = x ? [](int p) { } : [](int p) { };
}

但是,如果 lambda 的参数声明为 auto

int main()
{
    bool x = true;
    auto a_lambda = x ? [](auto p)  { } : [](auto p) { };
}

代码不再编译,报错:

main.cpp:4:23: error: operands to ?: have different types 'main()::<lambda(auto:1)>' and 'main()::<lambda(auto:2)>'

    4 |     auto a_lambda = x ? [](auto p)  { } : [](auto p) { };

如果我强制分配给带有参数int 的函数,代码也不会编译:

#include <functional>

int main()
{
    bool x = true;
    // error: operands to ?: have different types 'main()::<lambda(auto:1)>' and 'main()::<lambda(auto:2)>'
    std::function<void(int)> a_lambda = x ? [](auto p)  { } : [](auto p) { };
}

分配给具有给定签名的函数后,参数列表中的auto 应适用于推导出为int 的两个lambda。

  • 为什么这两个 lambda 仍然是不同的类型?

  • 有没有办法修复第二个代码,即是否可以在参数列表中有 auto 的两个 lambdas 之间使用 ? 运算符“选择”,如果我确定的话对于两个 lambda,auto 将被推导出为相同的类型?

【问题讨论】:

  • 如果您确定推导的类型是什么,那么明确说明它有什么问题?
  • auto a_lambda = x ? function&lt;void(int)&gt;([](auto p) { }) : function&lt;void(int)&gt;([](auto p) { });
  • @cigien 就像任何其他auto 一样,当推导复杂时,有时使用它而不是“整理”类型更容易。
  • 我不知道为什么它会很复杂,因为您必须已经知道将其放入 std::function 的类型。

标签: c++ lambda


【解决方案1】:

您必须在三元运算符中明确指定至少一个表达式的类型。

这应该可行:

int main()
{
    bool x = true;
    auto a_lambda = x ? static_cast<void (*)(int)>([](auto p) { }) : [](auto p) { };
}

或者干脆

int main()
{
    bool x = true;
    auto a_lambda = x ? [](int p) { } : [](auto p) { };
}

【讨论】:

    【解决方案2】:

    x ? [](auto p){ } : [](auto p) { } 的类型不取决于它在(赋值)之后的使用方式。

    你必须直接在三元运算符中给出公共类型。例如:

    x ? static_cast<void(*)(int)>([](auto){}) : static_cast<void(*)(int)>([](auto){});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      相关资源
      最近更新 更多