0

I'm using explicit template instantiation. As far as I understand, because I'm instantiating in the header file, the following example should violate the one definition rule. But not a single compiler I've tried has a problem with it. What am I missing? Why does this work? And is it guaranteed to work on every compiler?

A.h:

#ifndef A_H
#define A_H

template<class T>
struct A
{
    T x;
};

// instantiate
template struct A<int>;
template struct A<float>;
template struct A<double>;

#endif

file1.cpp:

#include "A.h"

A<int> f();

int main()
{
    A<int> a = f();
}

file2.cpp:

#include "A.h"

A<int> f()
{
    return A<int>();
}
foxcub
  • 2,517
  • 2
  • 27
  • 27
  • Ill formed programs NDR (No diagnostic required) is allowed to not show error/warning. – Jarod42 Nov 10 '18 at 01:19
  • @Jarod42 I see, so this is ill-formed, but it's just that no compiler complains? In other words, I need to fix it. Would sticking these instantiations inside a function declared inline be correct? – foxcub Nov 10 '18 at 01:55
  • @1201ProgramAlarm Thanks for the pointer. It's very helpful. But same question as to Jarod42. – foxcub Nov 10 '18 at 01:55
  • The usual approach by the linker is to just pick one of the definitions and ignore the others. If they're all the same you shouldn't have a problem. – 1201ProgramAlarm Nov 10 '18 at 07:23

0 Answers0