我想要一个指向函数的函数指针,该函数将带有模板参数的类作为参数(参见 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;
}
关于c++ - 带模板的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392730/