在三元运算符中初始化捕获lambda [英] Initializing capturing lambda in ternary operator

查看:90
本文介绍了在三元运算符中初始化捕获lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过以下方式创建一个lambda:

I wanted to create a lambda in the following way:

auto l1 = condition ?
          [](){ return true; } :
          [number](){ return number == 123; };

但是,我遇到了错误:

operands to ?: have different types ‘main()::<lambda()>’ and ‘main()::<lambda()>’

显然,类型似乎是相同的.我以为,仅在一个lambda中捕获number可能是一个问题,但是对于这些我却得到了相同的错误:

Obviously, the types seem to be the same. I thought, that capturing number in only one of lambdas might be a problem, but I get the same error for these:

//check if capturing number in both lambdas would help
auto l2 = condition ?
          [number](){ return true; } :
          [number](){ return number == 123; };
//maybe the first lambda capture was optimised out? let's make sure:
auto l3 = condition ?
          [number](){ return number != 123; } :
          [number](){ return number == 123; };

我知道我可以用其他方法(如下)进行操作,但是我想知道造成这种现象的原因是什么.它是在启用了C ++ 14的GCC6.3.1上编译的.

I'm aware I can do it other way (below), but I'm wondering what is the cause of this behavior. It was compiled with GCC6.3.1, C++14 enabled.

//compiles      
auto l4 = condition ?
          [](const int){ return true; } :
          [](const int number){ return number == 123; };

推荐答案

每个 lambda表达式具有唯一的类型(即闭包类型,这是唯一的未命名的非工会非聚合类类型),即使具有相同的签名和函数体;编译器无法推断三元条件运算符的常见类型对于auto声明的变量,两种闭包类型根本不相关.

Every lambda expression has unique type (i.e. the closure type, which is a unique unnamed non-union non-aggregate class type), even with the same signature and function body; the compiler just can't deduce the common type of ternary conditional operator for the variable declared by auto, the two closure types are irrelevant at all.

您可以改用std::function.例如

std::function<bool()> l1;
if (condition)
     l1 = [](){ return true; };
else
     l1 = [number](){ return number == 123; };

对于l4,请注意具有空捕获列表的lambda表达式可以隐式转换为相应的函数指针.在这种情况下,它们都可以转换为相同的函数指针类型(即bool(*)(int)),然后可以将其推导为三元条件运算符的常见类型和l4的类型.

For l4, note that the lambda-expression with empty capture list could be converted to the corresponding function pointer implicitly. In this case both of them could be converted to the same function pointer type (i.e. bool(*)(int)), which then could be deduced as the common type of ternary conditional operator and the type of l4.

这篇关于在三元运算符中初始化捕获lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆