How to create a template function within a class? (C++)

后端 未结 4 1699
粉色の甜心
粉色の甜心 2020-11-30 16:45

I know it\'s possible to make a template function:

template
void DoSomeThing(T x){}

and it\'s possible to make a template

相关标签:
4条回答
  • 2020-11-30 17:16

    See here: Templates, template methods,Member Templates, Member Function Templates

    class   Vector
    {
      int     array[3];
    
      template <class TVECTOR2> 
      void  eqAdd(TVECTOR2 v2);
    };
    
    template <class TVECTOR2>
    void    Vector::eqAdd(TVECTOR2 a2)
    {
      for (int i(0); i < 3; ++i) array[i] += a2[i];
    }
    
    0 讨论(0)
  • 2020-11-30 17:19

    Yes, template member functions are perfectly legal and useful on numerous occasions.

    The only caveat is that template member functions cannot be virtual.

    0 讨论(0)
  • 2020-11-30 17:23

    The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.

    class Foo
    {
    public:
    template <typename T> void some_method(T t) {//...}
    }
    

    Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.

    // .h file
    class Foo
    {
    public:
    template <typename T> void some_method(T t);
    }
    
    // .cpp file
    //...
    template <typename T> void Foo::some_method(T t) 
    {//...}
    //...
    
    template void Foo::some_method<int>(int);
    template void Foo::some_method<double>(double);
    
    0 讨论(0)
  • 2020-11-30 17:31

    Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.

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