c++ - 运算符作为函数指针

标签 c++ operator-overloading function-pointers functor

我想让一个类根据类中的选项集实现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; 
};

但是,在您开始这样做之前,首先分析您的代码,看看通过 switchif 分支是否真的是瓶颈(可能不是!)。现代处理器具有非常违反直觉的性能特征,因此编译器可能能够生成比您想象的更好的代码。确保分支实际上对您来说成本太高而无法使用的唯一方法是分析您的代码。 (我所说的“分析”是指“进行精心设计的实验”,而不是“未经测试就产生直觉”。)

关于c++ - 运算符作为函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10240259/

相关文章:

c - C 中指向函数 (**ppf)() 的指针与指向函数 (*pf)() 的指针有何不同?

c++ - 我在 C++11 标准中缺少什么?

c++ - 将Xterm嵌入到C++中的Qt5应用程序中

c++ - 如果我只实现运算符 <,我可以使用运算符 == 吗?

带有 arg 函数的 Rust 函数

c++ - C++中指向成员函数的函数指针

c++ - 在树莓派中交叉编译的 qt 中构建应用程序时出错

c++ - 在运行时获取共享库C++的文件名

c++ - 在 C++ 中结合 getter 函数使用重载的比较运算符>

c++ - 指针上的下标运算符