在不使用其名称的情况下调用 class 的单个 public 函数
Call single public function of a class without using its name
是否可以根据 class 是唯一的 public 来调用它的功能?我的意思是:
类似于:
double res = MyClass().myFunction(n);
变成
double res = MyClass()[0](n);
Ideally I would have liked to call the function using a string with its name:
double res = MyClass().reflection("myFunction")(n);
但似乎不可能不浪费至少两倍的墨水来写函数名(函数指针和映射中对应的字符串)。
您可以重载 class 的调用运算符。这通常称为函子:
class MyClass {
public:
int operator()(int param) const {
return functionName(param);
}
int functionName(int param) const { return param; }
};
MyClass c;
int returnVal = c(3);
编辑地址 const
评论:
函数和运算符不需要是const
。只要函数不修改对象的状态,就应该将函数标记为 const
。这为调用该函数的人提供了更多信息,并且在多线程应用程序中尤为重要。如果您调用的函数不是 const,您可以从重载中删除 const。
有关详细信息,请参阅 this。
您可以通过重载 []
运算符来获得与您编写的内容接近的内容:
#include <iostream>
class MyClass
{
public:
double operator [] (int n)
{
return functionName (n);
}
private:
double functionName (int n)
{
return n + 1;
}
};
int main ()
{
int n = 1;
double res = MyClass ()[n];
std::cout << "res: " << res << std::endl;
return 0;
}
查看结果here。
请注意 here,传递给 []
的参数显示为 size_t,但我认为这不是标准的要求。我也能够让它为 std::string
工作。
#include <iostream>
#include <string>
class MyClass
{
public:
std::string operator [] (std::string n)
{
return functionName (n);
}
private:
std::string functionName (std::string n)
{
return n + '1';
}
};
int
main ()
{
std::string n = "test";
std::string res = MyClass ()[n];
std::cout << "res: " << res << std::endl;
}
见here
是否可以根据 class 是唯一的 public 来调用它的功能?我的意思是:
类似于:
double res = MyClass().myFunction(n);
变成
double res = MyClass()[0](n);
Ideally I would have liked to call the function using a string with its name:
double res = MyClass().reflection("myFunction")(n);
但似乎不可能不浪费至少两倍的墨水来写函数名(函数指针和映射中对应的字符串)。
您可以重载 class 的调用运算符。这通常称为函子:
class MyClass {
public:
int operator()(int param) const {
return functionName(param);
}
int functionName(int param) const { return param; }
};
MyClass c;
int returnVal = c(3);
编辑地址 const
评论:
函数和运算符不需要是const
。只要函数不修改对象的状态,就应该将函数标记为 const
。这为调用该函数的人提供了更多信息,并且在多线程应用程序中尤为重要。如果您调用的函数不是 const,您可以从重载中删除 const。
有关详细信息,请参阅 this。
您可以通过重载 []
运算符来获得与您编写的内容接近的内容:
#include <iostream>
class MyClass
{
public:
double operator [] (int n)
{
return functionName (n);
}
private:
double functionName (int n)
{
return n + 1;
}
};
int main ()
{
int n = 1;
double res = MyClass ()[n];
std::cout << "res: " << res << std::endl;
return 0;
}
查看结果here。
请注意 here,传递给 []
的参数显示为 size_t,但我认为这不是标准的要求。我也能够让它为 std::string
工作。
#include <iostream>
#include <string>
class MyClass
{
public:
std::string operator [] (std::string n)
{
return functionName (n);
}
private:
std::string functionName (std::string n)
{
return n + '1';
}
};
int
main ()
{
std::string n = "test";
std::string res = MyClass ()[n];
std::cout << "res: " << res << std::endl;
}
见here