模板静态成员函数指针初始化

问题描述:

template<class K> 
class Cltest 
{ 
public: 
    static double (K::*fn)(double); 
}; 

template<class K> 
double K::*Cltest<K>::fn(double) = NULL; 

如何初始化静态成员函数指针?模板静态成员函数指针初始化

+0

我不确定,但不能像你初始化为0一样吗? – 2012-03-09 14:25:43

您需要将大括号中的*fn括起来。
修正语法:

template<class K> 
double (K::*Cltest<K>::fn)(double) = 0; 
+0

一如既往,我迟到了5秒;) – 2012-03-09 14:34:19

如果使用适当的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是该类型的变量

+1

是的,好点。删除了我的答案。 – 2012-03-09 14:42:16

+0

这对我很好,我会用它,谢谢! – Jona 2012-03-09 15:27:59