2010-10-21 98 views
23

考虑以下模板类。C++模板 - 多种类型

template <class T> 
class MyClass 
{ 
    void MyFunc(); 
} 

template <class T> 
void MyClass<T>::MyFunc() 
{ 
    //...implementation goes here 
} 

我需要添加其他功能myfunc2所它接受一个额外的模板ARG T2

template <class T> 
class MyClass 
{ 
    void MyFunc(); 

    template <class T2> 
    static void MyFunc2(T2* data); 
} 

template <class T> 
void MyClass<T>::MyFunc() 
{ 
    //...implementation goes here 
} 

template <class T, class T2> 
void MyClass<T>::MyFunc2(T2* pData) 
{ 
    //...implementation goes here 
} 

我使用VS 2008的编译器。我得到错误

error C2244: unable to match function definition to an existing declaration 

函数定义和声明应该如何在这种情况下看起来像。

+2

通常情况下,在类模板定义中内联模板成员函数的定义会更容易,以避免所有这些小问题 – 2010-10-21 11:12:27

回答

24
template <class T> 
template <class T2> 
void MyClass<T>::MyFunc2(T2* pData) 
{ 
    //...implementation goes here 
} 

编辑2:

$ 14.5.2/1 - “A模板可以是一个类或类 模板内声明 ;这样的模板被称为 构件模板的成员模板。 可定义在其类别内部或外部 定义或类别模板 定义 类别模板的成员模板定义在类别模板的 之外定义 应使用 模板的 模板的 模板参数以及 模板的 模板参数。

+0

我总是发现这个语法awkw ard,嵌套类不会更好... – 2010-10-21 17:15:00

+0

@Chubsdad:原始模板成员函数声明中的static关键字怎么样?在实施中放弃它有效吗? – 2011-08-10 23:33:55

18

你在做什么是好的,尝试了这一点:

template <typename S,typename T> 
struct Structure 
{ 
    S s ; 
    T t ; 

} ; 

int main(int argc, const char * argv[]) 
{ 
    Structure<int,double> ss ; 
    ss.s = 200 ; 
    ss.t = 5.4 ; 

    return 1; 
} 

此代码的工作。如果你得到奇怪的错误,看看你是否向前声明Structure只使用1个。模板参数(这就是我在做的)