c++ - 带模板的函数指针

标签 c++ function templates pointers function-pointers

我想要一个指向函数的函数指针,该函数将带有模板参数的类作为参数(参见 main)。我相信我接近正确的语法,但我收到编译错误:“模板声明不能出现在 block 作用域”。

#include <iostream>
#include <array>

template<int N>
class NumberHolder
{
public:
  NumberHolder();
  int x_;
};

template<int N>
NumberHolder<N>::NumberHolder() : x_(N) {}

template<int N, int M>
void add(NumberHolder<N>& nh)
{
  nh.x_ += M;
}

template<int N, int M>
void mult(NumberHolder<N>& nh)
{
  nh.x_ *= M;
}

int main()
{
  NumberHolder<3> nh;

  //using f_ptr = void(*)(NumberHolder<3>&); // Compiles
  template<int N> using f_ptr = void(*)(NumberHolder<N>&); // Doesn't compile

  std::array<f_ptr, 2> operations;
  operations[0] = &add<3, 41>;
  operations[1] = &mult<3, 8>;

  for (int i = 0; i < operations.size(); ++i)
  {
    operations[i](nh); 
  }
  std::cout << nh.x_ << std::endl;
  return 0;
}

最佳答案

您必须将您的模板别名移到本地范围之外:

template <int N> using f_ptr = void (*)(NumberHolder<N>&);

int main()
{
    const std::array<f_ptr<3>, 2> operations {&add<3, 41>, &mult<3, 8>};
    NumberHolder<3> nh;

    for(const auto& operation : operations) {
        operation(nh);
    }
    std::cout << nh.x_ << std::endl;
    return 0;
}

Live example .

关于c++ - 带模板的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392730/

相关文章:

c++ - 指向 vector 中对象的指针有时指向 vector 中的不同对象

c++ - BOOST SPIRIT 解析 - 创建正确的 AST 树

Swift:如何修复超出范围时返回 nil 的函数

javascript - 如何从作为参数传入的嵌套函数访问参数

c++ - 如何在编译时检查类型是否为多态

c++ - 减少重载函数的冗余代码(const& vs &)

jquery - 输入 jquery 时进行验证

php - HTML 模板 -- php?

javascript - 如何在 Iron Router Meteor 中查看当前路线

c++ - OpenGL 是否仅针对 vSync fps 更新屏幕?