C++ 模板 - 多种类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3986765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:12:36  来源:igfitidea点击:

C++ Template - Multiple types

c++templates

提问by SysAdmin

consider the following template class.

考虑以下模板类。

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

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

I need to add another function MyFunc2which accepts an additional Template arg T2i.e

我需要添加另一个函数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
}

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

我正在使用 VS 2008 编译器。我收到错误

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

How should the the functions definition and declaration look like in this case.

在这种情况下,函数定义和声明应该如何。

采纳答案by Chubsdad

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

EDIT 2:

编辑2:

$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."

$14.5.2/1 - “可以在类或类模板中声明模板;这样的模板称为成员模板。可以在其类定义或类模板定义之内或之外定义成员模板。在其类模板定义之外定义的类模板应使用类模板的模板参数指定,后跟成员模板的模板参数。

回答by bobobobo

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 declaredStructureusing only 1 template parameter (that's what I was doing).

此代码有效。如果您遇到奇怪的错误,请查看您是否仅使用 1 个模板参数进行了转发声明Structure(这就是我正在做的)。

回答by Hafedh

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