Search code examples
c++11conditional-statementspointer-to-member

Can conditional operator be used to toggle between two class member function calls


Consider this:

int func1( int i );
int func2( int i );

Conditional operator can be used like that:

int res = (cond)?func1(4):func2(4);

Or, if both may use the same parameter:

int res = ((cond)?func1:func2)(4);

Now, what about member functions of a class:

class T
{
public:
    T( int i ) : i(i) {}

    int memfunc1() { return 1*i; }
    int memfunc2() { return 2*i; }

private:
    int i;
};

I tried this, but it does not work:

T t(4);
int res2 = t.((cond)?memfunc1:memfunc2)();

...tried other syntax too ((t.*((cond)?&(T::memfunc1):&(T::memfunc2)))()) with no success...

Is that doable and then what would be the good syntax? One line code answer are preferable (using a temporary auto variable to store pointer to function would be too easy...;-)


Solution

  • § 5.3.1 [expr.unary.op]/p4:

    A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses. [ Note: that is, the expression &(qualified-id), where the qualified-id is enclosed in parentheses, does not form an expression of type “pointer to member.” Neither does qualified-id, because there is no implicit conversion from a qualified-id for a non-static member function to the type “pointer to member function” as there is from an lvalue of function type to the type “pointer to function” (4.3). Nor is &unqualified-id a pointer to member, even within the scope of the unqualified-id’s class. — end note ]

    If it still doesn't help, you can uncover the correct syntax below:

    (t.*(cond ? &T::memfunc1 : &T::memfunc2))()