inline template function?

后端 未结 4 1792
梦毁少年i
梦毁少年i 2020-12-29 02:38

Do I need inline template functions if they are included in several cpp files? Thanks.

template inline QString GetText(         


        
4条回答
  •  天涯浪人
    2020-12-29 03:17

    Yes, you need the inline specifier there.

    The ODR (one-definition rule) states that there must be exactly one definition of a variable, function, class, enum or template. Exceptions relevant for your question are listed in §3.2/5 (C++11) (emphasis mine):

    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. [...]

    Template specializations for which all parameters are specified (i.e. explicit specializations) are not listed there, and §14.7.3/12 says:

    An explicit specialization of a function template is inline only if it is declared with the inline specifier or defined as deleted, and independently of whether its function template is inline. [ Example:

    template void f(T) { /∗ ... ∗/ }
    template inline T g(T) { /∗ ... ∗/ }
    template<> inline void f<>(int) { /∗ ... ∗/ }  // OK: inline
    template<> int g<>(int) { /∗ ... ∗/ }          // OK: not inline
    

    — end example ]

提交回复
热议问题