【问题标题】:Function pointer as parameter in a class method declaration函数指针作为类方法声明中的参数
【发布时间】:2014-09-12 04:38:55
【问题描述】:

我正在尝试创建一个将函数指针(常规 C 函数指针,而不是类方法指针)作为参数的类方法。我搜索时唯一出现的是如何创建/使用成员函数指针,我不想这样做。所以这里有一个方法,它接受一个函数指针,该指针返回一个布尔值并接受两个整数作为参数:

class ExampleA
{
public:
  void sort(WHAT_GOES_HERE); // Should it be the same as method definition below?
};

ExampleA::sort(bool (*customSort)(int, int)) // Hopefully this is correct
{
  // Use function pointer
}

有没有办法在方法声明中声明参数而不用像带int参数的方法一样命名?

class ExampleB
{
public:
  void someFunction(int); // Not named here
};

ExampleB::someFunction(int varName)
{
  // do whatever
}

【问题讨论】:

标签: c++ pointers


【解决方案1】:

是的!把名字去掉就行了。

void sort(bool (*)(int, int));

【讨论】:

    【解决方案2】:
    bool (*)(int, int)
    

    基本上,去掉变量名就可以得到一个没有变量名的声明。

    但是,通常最好使用 typedef:

    typedef bool(*custom_sorter)(int, int);
    
    class ExampleA {
    public:
      void sort(custom_sorter);
    };
    
    ExampleA::sort(custom_sorter customSort) {
      // Use function pointer
    }
    

    这是等价的。

    由于我个人讨厌声明函数指针的语法,在 C++11 中我可能会这样做:

    template<class T> using type=T;
    
    ...
    
      void sort(type<bool(int,int)>*)
    

    将签名类型放在一起,然后我在它后面加上一个* 使其成为一个指针。

    但我很奇怪。

    【讨论】:

    • 我想这可能是我第一次看到模板化的using 声明。甚至不知道这是合法的......
    • ...那是因为它是一个新的 C++11 特性。不错。
    【解决方案3】:

    声明应与定义匹配,因此WHAT_GOES_HERE 应为bool (*customSort)(int, int),并且函数定义应指定返回类型void。

    您可以选择省略名称customSort,没有区别。

    这有点不灵活;考虑将其设为接受函子或std::function 而不是函数指针的函数模板;那么您的调用者可以使用更广泛的函数调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多