Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the following program compile according to standard?

After my discovery of incosistency between MSVC and GCC (probably clang too) in compilation and linking of the same code, I've become curious should this program actually compile and link and thus it's bug in MSVC (which reports a linker error) or should I write it differently. The program consist of 3 files:

C.h

template <typename T>
struct A
{
    void func() {};
};

template <>
void A<int>::func ();

A.cpp:

#include "C.h"
int main()
{
    A<int> x;
    x.func();
}

B.cpp:

#include "C.h"
template <>
void A<int>::func()
{
}

The resulting linker error from MSVC is:

A.obj : error LNK2019: unresolved external symbol "public: void __thiscall A::func(void)"

So basically it decides not to create symbol out of definition placed in B.cpp. The thing which makes me strongly suspect it as a bug is that moving unspecialized definition of func out of struct definition and even placing it above specialization declaration makes program linnking successful, but I would like to be sure.

So my question is - should this program be compiled and linked without errors by a conformant compiler/linker?

like image 394
Predelnik Avatar asked Sep 06 '15 10:09

Predelnik


1 Answers

From the standard :

© ISO/IEC N4527 14.6.4.1 Point of instantiation [temp.point] 1 For a function template specialization, a member function template specialization, or a specialization for a member function or static data member of a class template, if the specialization is implicitly instantiated because it is referenced from within another template specialization and the context from which it is referenced depends on a template parameter, the point of instantiation of the specialization is the point of instantiation of the enclosing specialization. Otherwise, the point of instantiation for such a specialization immediately follows the namespace scope declaration or definition that refers to the specialization.

In this case I think this means at C.h where the "scope declaration" occurs. If this is the case then your code should link with a standard compliant tool chain. I could be misinterpreting this...

like image 112
William Jones Avatar answered Sep 24 '22 02:09

William Jones