I have a dilemma about how I should pass a function pointer that will be used extensively by a class throughout the object lifetime. I have thought of 2 solutions:
- Passing the function pointer to the constructor and storing it inside the class:
using Func = int(*)(int);
class A
{
public:
explicit A(int n, Func f)
: _f(f), _n(n)
{}
int Process()
{
return f(n);
}
private:
Func _f;
int _n;
};
- Or using a template parameter:
using Func = int(*)(int);
template<Func f>
class A
{
public:
explicit A(int n)
: _n(n)
{}
int Process()
{
return f(n);
}
private:
int _n;
};
I think the template solution is more elegant but I am not really sure if it is the best solution. And as a subsidiary question in the template solution, if only the Process method is using the template parameter can I still put the constructor in a source file and keep the Process method in the header file?