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 old drafts of standard [1][2], and assuming linkage part doesn't change too much (except for anonymous namespaces). The class template has external linkage by 3.5p4 and 14p4. If that's the case, I would expect 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://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf [2] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
inline
or have internal linkage. – dypextern template class std::vector<int>
all the time. – nocte107