Agrim Pathak
Agrim Pathak

Reputation: 3207

Function pointers with templates

I want a function pointer that points to a function that takes as argument a class with a template parameter (see main). I believe I'm close to the right syntax, but I receive the compilation error: "a template declaration cannot appear at block scope".

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

Upvotes: 0

Views: 758

Answers (1)

Jarod42
Jarod42

Reputation: 217275

You have to move your template alias outside of local scope:

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.

Upvotes: 1

Related Questions