这种向前声明模板变量合法的方法吗?

时间:2018-11-28 11:20:12

标签: c++ language-lawyer forward-declaration template-variables

下面的代码中列出了常量模板变量的前向声明示例,该示例变量同时在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违反?

Linking phase error demonstration


注意:在此answers to this questions中,他们似乎忽略了将变量声明为extern const的可能性。

0 个答案:

没有答案