jeudi 28 mai 2015

Linkage of explicit class template instantiation

Are multiple instantiations of the same class template with the same type allowed in different compilation units? What about function templates?

A sample code is as follow:

test.hpp

template <typename T>
class A
{
    public:
        T out();
};

template <typename T>
T A<T>::out()
{
    return T(1);
}

test1.cpp

#include "test.hpp"
template class A<int>;
int testFn()
{
    return A<int>().out();
}

test2.cpp

#include "test.hpp"
template class A<int>;
extern int testFn();
int main()
{
    return testFn() == A<int>().out();
}

If I run

g++ -std=c++11 test1.cpp test2.cpp -o test

it compiles without complaining duplicated definitions.

I was refering to an old draft of standard [1], and assuming linkage part doesn't change too much (except for anonymous namespaces). The class template has external linkage by 3.5.4 and 14.0.4. If that's the case, I would reason that g++ should complain duplicated definitions of A::out(). Am I missing something here?

What if test.hpp defines a function template without "static" or "inline" instead?

Thank you.

[1] http://ift.tt/1JaUT74

Aucun commentaire:

Enregistrer un commentaire