2011-11-16 139 views
1

第一次我在同一時間使用模板和指向成員函數的指針,並且偶然發現了以下問題。使用模板函數指針聲明模板函數

我聲明瞭一個typedef的結構代理,因爲模板和typedefs不能一起工作(我知道這應該可以在C++ 11中,MSVC++不會接受它)。現在我想聲明一個使用模板類型代理的模板化(!)函數。這是編譯時導致錯誤的原因。請看下面的(簡化)代碼,我添加了一些例子來澄清問題。

我正在使用標準VC++ 2010(無CLR/CLI)。

template<typename T> 
struct Proxy 
{ 
    typedef bool (CClass::*MethodPtr)(const T* const objectX); 
} 

class CClass 
{ 
    // warning: dependent name is not a type 
    // error:: Method can not be a template definition 
    template<typename T> 
    bool Method(Proxy<T>::MethodPtr); 

    // this works, but i want to specify T instead of int of course 
    template<typename t> 
    bool method(Proxy<int>::MethodPtr); 

    // this is what i use 
    template<typename T> 
    bool Method(bool (CClass::*MethodPtr)(const T* const objectX)); 
} 

template<typename T> 
bool CClass::Method(bool (CClass::*MethodPtr)(const T* const objectX)) 
{ 
    // next line compiles without problems 
    Proxy<T>::MethodPtr ptr2; 
} 
+0

您需要在函數原型中使用'typename'。 – moshbear

回答

5

您需要使用typename來指示從屬名稱的類型;特別的Method第一個聲明應該是:

template<typename T> 
bool Method(typename Proxy<T>::MethodPtr); 

和你說行編譯沒有問題(但僅僅是因爲VC++具有接受形成不良代碼的「擴展」)應該是:

// next line compiles without problems 
typename Proxy<T>::MethodPtr ptr2; 

您還在類定義之後缺少分號,並且在Proxy的定義之前提供了CClass的前向聲明。

+1

在ideone執行操作:http://ideone.com/TSJml –

2
// warning: dependent name is not a type 
// error:: Method can not be a template definition 
template<typename T> 
bool Method(Proxy<T>::MethodPtr); 

MethodPtr依賴於模板參數T,你應該使用typename

// next line compiles without problems 
Proxy<T>::MethodPtr ptr2; 

你應該使用typename有作爲,不知道爲什麼它編譯。