【问题标题】:Function pointers with templates带模板的函数指针
【发布时间】:2014-12-10 03:11:28
【问题描述】:

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

#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;
}

【问题讨论】:

  • 您只能通过使用 C++14 的 变量模板 来接近它。但是这些和所有模板一样,不能在本地声明。
  • 无论如何,您不能将类模板用作类,也不能将变量模板用作变量。用 Stephan T. Lavavej 的话来说:“你不能吃饼干刀。” std::array&lt;f_ptr, 2&gt; 因此不能合法:f_ptr 是一个模板,std::array 需要一个类型作为它的第一个模板参数。

标签: c++ function templates pointers function-pointers


【解决方案1】:

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

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2019-10-20
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    相关资源
    最近更新 更多