【发布时间】:2019-10-12 19:57:50
【问题描述】:
对于如何传递一个函数指针,该函数指针将在整个对象生命周期中被类广泛使用,我感到两难。我想到了2个解决方案:
- 将函数指针传递给构造函数并将其存储在类中:
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;
};
- 或者使用模板参数:
using Func = int(*)(int);
template<Func f>
class A
{
public:
explicit A(int n)
: _n(n)
{}
int Process()
{
return f(n);
}
private:
int _n;
};
我认为模板解决方案更优雅,但我不确定它是否是最佳解决方案。 并且作为模板解决方案中的一个附属问题,如果只有Process方法使用模板参数,我是否仍然可以将构造函数放在源文件中,并将Process方法保留在头文件中?
【问题讨论】:
-
模板方法的另一个好处是您对函数施加的任何约束都可以在编译时强制执行。