来自initializer_list的三元运算符+ C ++ 11构造函数 [英] Ternary operator + C++11 constructor from initializer_list
问题描述
在开发应用程序时,我遇到以下问题.当给定的函数指针为null时,我想返回一个空的 std :: list< string>
,否则返回该函数的结果.这是我的代码的简化版本:
typedef std :: list< std :: string>(* ParamGenerator)();std :: list< std :: string>foo(){/* ... */ParamGenerator generator = ...;如果(发电机)返回generator();别的返回 {};}
但是,在这些情况下,我通常喜欢使用三元(?:
)运算符,因此我尝试以这种方式使用它(照常):
返回生成器?发电机() : {};
但是出现了这个错误:
somefile.cpp:143:46:错误:"{"令牌之前的预期主表达式somefile.cpp:143:46:错误:在"{"令牌之前应为;"
这是否意味着我不能使用三元运算符从 initializer_list
返回使用其构造函数创建的对象?有什么特别的原因吗?
8.5.4.1中的标准编写:列表初始化
注意:可以使用列表初始化
- 作为变量定义(8.5)中的初始化程序
- 作为新表达式(5.3.4)中的初始化程序
- 在返回声明中(6.6.3)
- 作为函数参数(5.2.2)
- 作为下标(5.2.1)
- 作为构造函数调用的参数(8.5、5.2.3)
- 作为非静态数据成员(9.2)的初始化程序
- 在内存初始化器中(12.6.2)
- 在作业的右侧(5.17)
它们都不是三元运算符.简约的 return 1?{}:{};
也是无效的,您想要的是不可能的.
当然,您可以显式调用构造函数 std :: list< std :: string> {}
,但是我建议写出 if
- else
-就像您已经做过的一样.
While developing an application, I had the following problem. I wanted to return an empty std::list<string>
when a given function pointer was null, or the result of that function otherwise. This is a simplified version of my code:
typedef std::list<std::string> (*ParamGenerator)();
std::list<std::string> foo() {
/* ... */
ParamGenerator generator = ...;
if(generator)
return generator();
else
return {};
}
However, I usually like to use the ternary (?:
) operator in these cases, so I tried using it this way (as usual):
return generator ? generator() : {};
But got this error:
somefile.cpp:143:46: error: expected primary-expression before ‘{’ token
somefile.cpp:143:46: error: expected ‘;’ before ‘{’ token
Does this mean I can't use the ternary operator to return objects created using their constructor from an initializer_list
? Is there any particular reason for that?
Standard writes in 8.5.4.1: List-initialization
Note: List-initialization can be used
- as the initializer in a variable definition (8.5)
- as the initializer in a new expression (5.3.4)
- in a return statement (6.6.3)
- as a function argument (5.2.2)
- as a subscript (5.2.1)
- as an argument to a constructor invocation (8.5, 5.2.3)
- as an initializer for a non-static data member (9.2)
- in a mem-initializer (12.6.2)
- on the right-hand side of an assignment (5.17)
Nothing of them is a ternary operator. The more minimalistic return 1?{}:{};
is invalid too, what you want is impossible.
Of course you can explicitly call the constructor std::list<std::string>{}
, but I would recommend to write out the if
-else
-block as you already did.
这篇关于来自initializer_list的三元运算符+ C ++ 11构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!