Ternary operator and function signature

Say I have a C ++ class with two functions like

class MyClass { bool Foo(int val); bool Foo(string val); } 

Is it possible to use the ternary operator as follows:

 MyClassInstance->Foo(booleanValue?24:"a string"); 

and have a different MyClass function MyClass depending on the value of booleanValue ?

+8
c ++ ternary-operator
source share
4 answers

Not with a ternary operator. The type of the triple expression is the general type of its second and third operands; unless they have a generic type, you cannot use it. So just use the usual if :

 if (booleanValue) MyClassInstance->Foo(24); else MyClassInstance->Foo("a string"); 
+21
source share

The ternary conditional expression type is a generic type 2, which both operands are con & shy; ver & shy; tible. You can definitely not run the “dynamic overload resolution” as you seem to suggest.

Since there is no common type for int and char const * , the code will not even compile (as you are sure, and shyly noticed when you tested it).

(You may be delighted that the terminological condition is used precisely because of semantics when implementing the class std::common_type , together with decltype .)

(If the condition is known statically, for example sizeof(int) != 7 , then you can use the spe & shy; cia & shy; lization pattern to write similar code that does conditional overload resolution, but, of course, statically.)

+7
source share

Not. To execute overload resolution, the compiler will ask: "What is the type of booleanValue?24:"a string" ?". This question cannot be answered.

+5
source share

No, this is not allowed.

Overloads are compilation time, so it cannot work at run time this way.

This is not often found in code that you would like to do just that, however sometimes with iostream there is a desire to do something like:

os << ( condition ? var1 : var2 )

where var1 and var2 are of different types. This also does not work.

You can do:

 MyClassInstance->Foo( booleanValue ? boost::any(24) : boost::any("a string") ); 
+5
source share

All Articles