C++ Template - Multiple types

前端 未结 3 1031
旧时难觅i
旧时难觅i 2021-01-30 17:08

consider the following class template:

template 
class MyClass
{
   void MyFunc();
};

template 
void MyClass::MyFunc()
{
          


        
相关标签:
3条回答
  • 2021-01-30 17:22

    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 讨论(0)
  • 2021-01-30 17:23

    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).

    0 讨论(0)
  • 2021-01-30 17:34
    template <class T>
    template <class T2> 
    void MyClass<T>::MyFunc2(T2* pData) 
    { 
      //...implementation goes here 
    }
    

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

    0 讨论(0)
提交回复
热议问题