Why full specialization of template function is not picked up from the .cpp file without declaration?

后端 未结 3 1137
盖世英雄少女心
盖世英雄少女心 2021-01-23 04:42

Following code generate no compilation/linker error/warning:

// A.h
#include
struct A
{
  template
  static void foo (T t)
  {
         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-23 05:41

    Why compiler is not able to pick up the correct A::foo(double) in case of main.cpp ?

    The problem is that in a separate compilation model without a declaration available in the header the compiler wouldn't possibly know whether an specialization exists in any translation unit that will later be linked or whether it needs to instantiate the template. The decision in the language is that the absence of a declaration means that there is no manual specialization of the template, and thus the compiler needs to generate one now.

    is having 2 different version of the same function an Undefined Behavior ?

    Yes it is. Whether one of the specializations was automatically generated or not, the fact is that it is undefined behavior as it is a violation of the One Definition Rule (there are multiple definitions of the same symbol).

提交回复
热议问题