【问题标题】:Templated static member function pointer initialization模板化静态成员函数指针初始化
【发布时间】:2012-03-09 22:56:34
【问题描述】:
template<class K>
class Cltest
{
public:
static double (K::*fn)(double);
};
template<class K>
double K::*Cltest<K>::fn(double) = NULL;
如何初始化静态成员函数指针?
【问题讨论】:
标签:
c++
templates
initialization
【解决方案1】:
您需要将*fn 括在大括号中。
更正语法:
template<class K>
double (K::*Cltest<K>::fn)(double) = 0;
【解决方案2】:
如果您使用适当的 typedef 来简化语法,那么这样做会容易得多:
template<class K>
class Cltest
{
public:
typedef double (K::*Fn)(double); //use typedef
static Fn fn;
};
template<class K>
typename Cltest<K>::Fn Cltest<K>::fn = 0;
//Or you can initialize like this:
template<class K>
typename Cltest<K>::Fn Cltest<K>::fn = &K::SomeFun;
使用typedef,您实际上将函数的类型与变量名称分开。现在您可以分别查看它们,从而更容易理解代码。例如,上面的Cltest<K>::Fn 是类型,Cltest<K>::fn 是该类型的变量。