Search code examples
c++ternary-operatorfunction-signature

Ternary operator and function signature


Let's 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 like this

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

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


Solution

  • Not with the ternary operator. The type of a ternary expression is the common type of its second and third operands; if they have no common type you can't use it. So just use an ordinary if statement:

    if (booleanValue)
        MyClassInstance->Foo(24);
    else
        MyClassInstance->Foo("a string");