Are methods of templated classes implied inline li

2019-04-11 19:18发布

问题:

Are methods of templated classes implied inline linkage (not talking about the inline optimization), or is it just templated methods which are?

// A.h

template<typename T>
class A
{
public:
    void func1();                       //  #1
    virtual void func2();               //  #2
    template<typename T2> void func3(); //  #3
};

template<typename T>
void A<T>::func1(){}    //  #1

template<typename T>
void A<T>::func2(){}    //  #2

template<typename T>
template<typename T2>
void A<T>::func3<T2>(){}    //  #3

Are all the above cases inline [linkage]? (Should I explicitly write inline for any of them)?

回答1:

Template functions and member functions of template classes are implicitly inline if they are implicitly instantiated, but beware template specializations are not.

template <typename T>
struct test {
    void f();
}
template <typename T>
void test<T>::f() {}           // inline

template <>
void test<int>::f() {}           // not inline

By lack of a better quote:

A non-exported template must be defined in every translation unit in which it is implicitly instantiated (14.7.1), unless the corresponding specialization is explicitly instantiated (14.7.2) in some translation unit; no diagnostic is required