2012-03-09 232 views
2
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

回答

4

您需要將大括號中的*fn括起來。
修正語法:

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

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

4

如果使用適當的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