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
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 theif–else-block as you already did.