This code compiles:
std::string f(bool a, std::string const& b)
{
if (a) return b;
return {};
}
This code also compiles:
std::string f(bool a, std::string const& b)
{
return a ? b : std::string{};
}
This code does not compile:
std::string f(bool a, std::string const& b)
{
return a ? b : {};
}
Given that both result values of the ?:
operator are required to be the same type, why doesn't it infer the type like it does in the first example?
It appears that this question might have a similar answer to this (which essentially boils down to "because nobody thought about it when writing the language specification"). However I still think it's useful to retain this question as the question itself is different, it's still sufficiently surprising, and the other wouldn't come up in searches for this issue.
{}
doesnt have a type. – Geology{}
is an initalizer list (which cannot be used here) live: godbolt.org/z/imYL6q – Aleron{}
withstd::initializer_list<char>()
also compiles. – Benedix