Difference between member functions for a template class defined inside and outside of the class

后端 未结 3 1279
太阳男子
太阳男子 2021-02-14 11:43

Is there a difference between defining member functions for a template class inside the class declaration versus outside?

Defined inside:

template 

        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-14 12:30

    I know this..I think it must be some what help full to u?

    defining a member function outside of its template
    

    It is not ok to provide the definition of a member function of a template class like this:

     // This might be in a header file:
     template 
     class xyz {
        void foo();
      };
    

    // ...

     // This might be later on in the header file:
      void xyz::foo() {
    // generic definition of foo()
       }
    

    This is wrong for a few reasons. So is this:

          void xyz::foo() {
             // generic definition of foo()
          }
    

    The proper definition needs the template keyword and the same template arguments that the class template's definition was declared with. So that gives:

           template 
              void xyz::foo() {
               // generic definition of foo()
                     }
    

    Note that there are other types of template directives, such as member templates, etc., and each takes on their own form. What's important is to know which you have so you know how to write each flavor. This is so especially since the error messages of some compilers may not be clear as to what is wrong. And of course, get a good and up to date book.

    If you have a nested member template within a template:

        template 
          struct xyz {
          // ...
          template 
           struct abc;
            // ...
           };
    

    How do you define abc outside of xyz? This does not work:

         template 
        struct xyz::abc { // Nope
          // ...
      };
    

    nor does this:

     template 
     struct xyz::abc { // Nope
    // ...
     };
    

    You would have to do this:

         template 
           template 
               struct xyz::abc {
                // ...
               };
    

    Note that it's ...abc not ...abc because abc is a "primary" template. IOWs, this is not good:

    // not allowed here: template template struct xyz::abc { };

提交回复
热议问题