我想让一个类根据类中的选项集实现operator()
几种不同的方法。因为这会被调用很多次,所以我不想使用任何分支。理想情况下,operator()
应该是一个可以用方法设置的函数指针。但是,我不确定这实际上会是什么样子。我试过:
#include <iostream>
class Test {
public:
int (*operator())();
int DoIt1() {
return 1;
}
int DoIt2() {
return 2;
}
void SetIt(int i) {
if(i == 1) {
operator() = &Test::DoIt1;
} else {
operator() = &Test::DoIt2;
}
}
};
int main()
{
Test t1;
t1.SetIt(1);
std::cout << t1() << std::endl;
t1.SetIt(2);
std::cout << t1() << std::endl;
return 0;
}
我知道如果我创建另一个函数指针并从 operator()
函数中调用它,它将起作用。但是有没有可能让 operator()
函数本身成为一个函数指针呢?与我发布的内容类似(无法编译)?
上面的代码给出了:
test.cxx:5:21: error: declaration of ‘operator()’ as non-function
test.cxx: In member function ‘void Test::SetIt(int)’:
test.cxx:17:16: error: ‘operator()’ not defined
test.cxx:19:16: error: ‘operator()’ not defined
test.cxx: In function ‘int main()’:
test.cxx:30:19: error: no match for call to ‘(Test) ()’
test.cxx:34:19: error: no match for call to ‘(Test) ()’
最佳答案
您的类需要以某种方式记住要使用的函数指针。将其存储为类成员:
class Test
{
public:
Test() : func(0) {}
int operator()() {
// Note that pointers to Test member functions need a pointer to Test to work.
return (this->*func)(); // undefined behavior if func == 0
}
void SetIt(int i) {
if(i == 1) {
func = &Test::DoIt1;
} else {
func = &Test::DoIt2;
}
}
private:
int DoIt1() {
return 1;
}
int DoIt2() {
return 2;
}
// Typedef of a pointer to a class method.
typedef int (Test::*FuncPtr)();
FuncPtr func;
};
但是,在您开始这样做之前,首先分析您的代码,看看通过 switch
或 if
分支是否真的是瓶颈(可能不是!)。现代处理器具有非常违反直觉的性能特征,因此编译器可能能够生成比您想象的更好的代码。确保分支实际上对您来说成本太高而无法使用的唯一方法是分析您的代码。 (我所说的“分析”是指“进行精心设计的实验”,而不是“未经测试就产生直觉”。)
关于c++ - 运算符作为函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10240259/