是否可以根据类是唯一的公共函数来调用类的函数?我的意思是:
就像是:
double res = MyClass().myFunction(n);
Run Code Online (Sandbox Code Playgroud)
变成
double res = MyClass()[0](n);
Run Code Online (Sandbox Code Playgroud)
double res = MyClass().reflection("myFunction")(n);
Run Code Online (Sandbox Code Playgroud)
但似乎不可能不浪费至少两倍的墨水来写函数名(函数指针和映射中的相应字符串)。
您可以重载类的调用运算符。这通常称为函子:
class MyClass {
public:
int operator()(int param) const {
return functionName(param);
}
int functionName(int param) const { return param; }
};
MyClass c;
int returnVal = c(3);
Run Code Online (Sandbox Code Playgroud)
编辑地址const
注释:
函数和运算符不需要是const
。const
只要函数不修改对象的状态,就应该标记函数。这为调用函数的人提供了更多信息,这在多线程应用程序中尤为重要。如果您调用的函数不是 const,您可以从重载中删除 const。
有关更多信息,请参阅此内容。