2

在下面的代码中列出了在 clang 和 gcc 上编译的常量模板变量的前向声明示例:

template<class T>
extern const T value;
template<class T>
const T value= 0;

auto test = value<int>;

template<class T>
extern const T value2;
template<class T>
constexpr T value2 =0;

auto test2 = value2<int>;

template<class T>
extern const T value3;
template<class T>
inline constexpr T value3 =0;

auto test3 = value3<int>;

不过,如果我声明变量非 const,gcc 会产生链接器错误:undefined reference to value4<int>undefined symbol value5<int>,但 clang 接受代码:

template<class T>
extern T value4;
template<class T>
T value4= 0;

auto test4 = value4<int>; //gcc linker error

template<class T>
extern T value5;
template<class T>
inline T value5=0;

auto test5 = value5<int>; //gcc linker error

最初,我对所有符合标准的用例充满信心。但是因为 gcc 在最后两种情况下会产生链接器错误,所以我想知道这些前向声明是否合法?gcc 是错误的还是我没有诊断要求的错误?前向声明后跟模板变量的内联定义作为value3value5在多个翻译单元中是否会导致 odr 违规?

链接相位错误演示


注意:在这个问题的答案中,他们似乎忽略了将变量声明为 extern const 的可能性。

4

0 回答 0