Reputation: 13156
Conditional operator cannot work with mixed data types, so:
bool cond = true;
cout << (cond?1:2) << endl;
cout << (cond?"msg1":"msg2") << endl;
cout << (cond?1:"msg") << endl;
On the last line, I get this error message:
error: incompatible operand types ('int' and 'const char *')
Is there a way to mix different types in such a statement, using a single line of code? I need to put it inside a preprocessor macro.
Compiler: clang 3.5
Upvotes: 3
Views: 1405
Reputation: 5388
statement (cond?1:"msg")
during compilation it self will leads to failure .
let a = (cond?1:"msg")
Compiler will translate this expression similar to this
if cond then
a = 1
else
a ="msg"
As we can see that type of value assigned to a
is changed from if to else.
But if you are in dynamic language that supports type changing then it will be valid.
So you should use
cout<<(cond?std::to_string( 1 ):"msg");
Upvotes: 1
Reputation: 1312
The << operator is overloaded for different data types, and when the code is compiled the compiler determines what overload function to call. This is why you can't have a function that return different possible datatypes: The compiler can't choose the right overload that way.
So, see (cond ? result1 : result2) as a function that requires exactly one return type, like any other function.
If you give a clearer example of what exactly you're trying to do, it might be easier to help you with it!
Cheers
Upvotes: 1
Reputation: 310990
For the last statement you can determine the common type like std::string
.
For example
std::cout << ( cond ? std::to_string( 1 ) : "msg" ) << std::endl;
Upvotes: 2
Reputation: 2309
The problem with this is that the ? : operators result in an assignment operation thus it can only assign the value to a single type and at compile time it is not possible to determine which one of the types should be used since the code branches as if an if statement is used. Imagine a method that returns a string in one case and an int in other, that's just not possible. What you can do is you can even out the types as @Vlad from Moscow suggested.
Upvotes: 2