三元运算符不适用于lambda函数 [英] ternary operator doesn't work with lambda functions

查看:106
本文介绍了三元运算符不适用于lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 std :: function< double()> 分配一个lambda表达式。此代码段有效

I am assigning to a std::function<double()> a lambda expression. This snippet works

if(fn_type==exponential)
    k.*variable = [=,&k](){ return initial*exp(-k.kstep*par); };
else
    k.*variable = [=,&k](){ return initial*pow(k.kstep, par); };

而如果我想使用三元运算符

whereas if I want to use the ternary operator

k.*variable = (fn_type==exponential ? [=,&k](){ return initial*exp(-k.kstep*par); } : [=,&k](){ return initial*pow(k.kstep, par); });

我收到以下错误:

error: no match for ternary ‘operator?:’ in <awfully long template error, because this whole thing is in a class defined in a function...>

这是gcc错误(我使用的是4.7.2)吗?否则,为什么标准中没有此限制?

Is this a gcc bug (I'm using 4.7.2)? Otherwise why is there this limit in the standard?

推荐答案

条件运算符的第二个和第三个操作数必须具有相同的类型或必须有一些共同的类型,它们都可以转换为编译器可以弄清楚的类型。编译器将考虑的转换很少。

The second and third operands of the conditional operator must have the same type or there must be some common type to which they can both be converted that the compiler can figure out. There are only a handful of conversions that the compiler will consider.

您的两个lambda表达式具有不同的类型,并且没有可以将它们都转换为的通用类型(不能考虑转换为用户定义的类型(例如 std :: function< double()> ),因为可能存在无限数量的有效目标类型)。

Your two lambda expressions have different types, and there is no common type to which they can both be converted (conversions to user-defined types, like std::function<double()>, cannot be considered because there are potentially an infinite number of valid target types).

您可以将每个操作数直接转换为 std :: function< double()>

You can directly convert each of the operands to std::function<double()>:

k.*variable = fn_type==exponential
    ? std::function<double()>([=,&k](){ return initial*exp(-k.kstep*par); })
    : std::function<double()>([=,&k](){ return initial*pow(k.kstep, par); });

但实际上,如果 / else

这篇关于三元运算符不适用于lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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