2011-11-16 141 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有作为,不知道为什么它编译。