开发者

How to define a nested member template outside a class template?

Consider the following class template:

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

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

I need to add another function template MyFunc2 which accepts a template argument T2 i.e.,

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

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

template <class T>
void MyClass<T>::MyF开发者_运维技巧unc()
{
  //...implementation goes here
}

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

I am using VS 2008 compiler. I am getting the error:

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

What should the function's definition and declaration look like in this case?


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

$14.5.2/1 - "A template can be declared within a class or class template; such a template is called a member template. A member template can be defined within or outside its class definition or class template definition. A member template of a class template that is defined outside of its class template definition shall be specified with the template-parameters of the class template followed by the template-parameters of the member template."


What you're doing is fine, try this out:

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;
}

This code works. If you're getting strange errors, see if you forward declared Structure using only 1 template parameter (that's what I was doing).


Try this one :

template <class T, class T2>
class MyClass
{
public:
    static void MyFunc2(T2* data);
};

template <class T, class T2>
void MyClass<T, T2>::MyFunc2(T2* pData)
{
    cout << "dummy " << *pData<< "\n";
}

Then

int main()
{
    cout << "Hello World!\n"; 
    MyClass<int, int> a;
    int *b = (int*)malloc(sizeof(int));
    *b = 5;
    a.MyFunc2(b);
}

Output

Hello World!
dummy 5
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜