x y*_*x y 5 c++ gcc clang c++14 c++17
//呃
template<int> extern int const i;
Run Code Online (Sandbox Code Playgroud)
// i.cpp
#include "i.h"
template<> extern int constexpr i<0> = 42;
Run Code Online (Sandbox Code Playgroud)
// main.cpp
#include "i.h"
int main()
{
return i<0>;
}
Run Code Online (Sandbox Code Playgroud)
在C++ 14/17模式下,这将返回带有clang的42,但是与gcc一起出错:"显式模板专门化不能有存储类".
这是gcc中的错误吗?
主变量模板必须声明为 extern,因为它是 const,并且我不希望在头文件中包含初始值设定项(就像普通的“extern int const i;”一样)。相反,我想要一些源文件中的专业化定义。
解决方案应该是删除专业化中的“外部”。
因为
[声明/说明符-7.1.1]存储类说明符不应在显式专业化中指定
理由是所有专业化都应该具有相同的链接(例如参见缺陷报告 605)。所以,这里的 clang 似乎是错误的。
不管怎样,考虑到编译器在这方面表现得很疯狂,解决方法可能是这样的
// i.h
template<int I> struct i_impl{ static const int value; };
template<int I> int const i = i_impl<I>::value;
// i.cpp
#include <i.h>
template<> const int i_impl<0>::value = 42;
Run Code Online (Sandbox Code Playgroud)