可以使用条件运算符在两个 class 成员函数调用之间切换
Can conditional operator be used to toggle between two class member function calls
考虑一下:
int func1( int i );
int func2( int i );
条件运算符可以这样使用:
int res = (cond)?func1(4):func2(4);
或者,如果两者可以使用相同的参数:
int res = ((cond)?func1:func2)(4);
现在,a class:
的成员函数呢?
class T
{
public:
T( int i ) : i(i) {}
int memfunc1() { return 1*i; }
int memfunc2() { return 2*i; }
private:
int i;
};
我试过了,但没用:
T t(4);
int res2 = t.((cond)?memfunc1:memfunc2)();
...也尝试了其他语法 ((t.*((cond)?&(T::memfunc1):&(T::memfunc2)))()
) 但没有成功...
这可行吗,那么好的语法是什么?一行代码答案更可取(使用临时自动变量存储指向函数的指针太容易了......;-)
§ 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 ]
如果仍然没有帮助,您可以在下面找到正确的语法:
(t.*(cond ? &T::memfunc1 : &T::memfunc2))()
考虑一下:
int func1( int i );
int func2( int i );
条件运算符可以这样使用:
int res = (cond)?func1(4):func2(4);
或者,如果两者可以使用相同的参数:
int res = ((cond)?func1:func2)(4);
现在,a class:
的成员函数呢?class T
{
public:
T( int i ) : i(i) {}
int memfunc1() { return 1*i; }
int memfunc2() { return 2*i; }
private:
int i;
};
我试过了,但没用:
T t(4);
int res2 = t.((cond)?memfunc1:memfunc2)();
...也尝试了其他语法 ((t.*((cond)?&(T::memfunc1):&(T::memfunc2)))()
) 但没有成功...
这可行吗,那么好的语法是什么?一行代码答案更可取(使用临时自动变量存储指向函数的指针太容易了......;-)
§ 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 ]
如果仍然没有帮助,您可以在下面找到正确的语法:
(t.*(cond ? &T::memfunc1 : &T::memfunc2))()