Template definitions outside class body

后端 未结 3 1030
梦如初夏
梦如初夏 2021-01-01 19:08

Is it O.K. to define virtual function of class template outside its body? Virtual function can not be inlined, but to avoid multiple definitions in compilation units they sh

相关标签:
3条回答
  • 2021-01-01 19:21

    Yes, it's OK even without inline. It works the same for ordinary member functions and static variables:

    // everything in the header:
    template <class T>
    class A
    {
      static int i;
    };
    
    template <class T>
    int A<T>::i=0;
    

    Standard quote: (3.2/5)

    There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements ...

    The requirements basically say the two definitions have to be identical.

    It doesn't work in case of regular classes. There has to be at most one definition in the whole program.

    0 讨论(0)
  • 2021-01-01 19:35

    You can define the functions there, as long as any code which needs to instantiate the function in question has visibility of that code at compile time (not link time).

    It's quite common to separate a template into 2 files, one being a traditional header, and the second being the implementation, as with non-templated functions and their implementation. The only difference is that you need to #include the template implementation file as well as the header when you want to use it.

    0 讨论(0)
  • 2021-01-01 19:36

    You can define template methods outside the class definition, in the same header, without using inline and without receiving multiple definition errors.

    That's because a template function doesn't generate a definition itself, if it's not fully specialized. To prove my point, the following:

    void C<int>::f(int)
    {
    }
    

    will result in a linker error, as the function has a definition in this case. (provided you include this in multiple translation units. If you mark it inline:

    inline void C<int>::f(int)
    {
    }
    

    the error no longer occurs.

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