C++ 我可以用一个常数模板吗?
我想编写以下代码:C++ 我可以用一个常数模板吗?,c++,c++11,C++,C++11,我想编写以下代码: template<typename T> const int a; template<> const int a<float>=5; template<> const int a<double>=14; template<> const int a<char>=6; template<> const int a<wchar>=33; 模板常量int a; 模板常数I
template<typename T> const int a;
template<> const int a<float>=5;
template<> const int a<double>=14;
template<> const int a<char>=6;
template<> const int a<wchar>=33;
模板常量int a;
模板常数INTA=5;
模板常数INTA=14;
模板常数INTA=6;
模板常数int a=33;
是的,如果您的编译器支持C++1y功能,您可以
template<typename T> const int a = 0;
template<> const int a<float> = 5;
template<> const int a<double> = 14;
template<> const int a<char> = 6;
template<> const int a<wchar_t> = 33;
template const int a=0;
模板常数INTA=5;
模板常数INTA=14;
模板常数INTA=6;
模板常数int a=33;
我在专门化的
和=
之间添加了空格,因为在其他情况下,clang会遇到解析错误
错误:直角括号和等号之间需要空格(使用“>=”)
<所有版本的C++(包括C++ 11)之前的解决方案:
模板
结构a{static const int value;};
模板常数int a::值=5;
模板常数int a::value=14;
模板常量INTA::value=6;
模板常数int a::值=33;
(请注意,问题使用了wchar
,这不是标准类型)
这有点笨拙,但很有效。他不希望常数的类型随类型参数而变化<代码>模板常数a=17代码>就是不起作用,而
模板常量int a=17代码>应该。但是我需要所有这些常量都是相同类型的id est int。上面的语法实现了吗?我检查了代码和最后两个字符。所以这不是我需要的。“有没有其他的行为方式?”GeorgeKourtis我误解了你的意图。更新了答案。@GeorgeKourtis不依赖。@Praetorian使用gnu g++似乎不起作用。我有其他选择吗?我知道这个解决方案,但我更喜欢你之前发布的另一个。看来只有宏才能解决这个问题?@GeorgeKourtis:既然他已经解决了问题,那就接受裁判官的答案吧。(据我所知,这正是您问题中的代码,加上一个默认值)constepr
函数也可以工作,在调用站点的线路噪音稍小一些(只是()
而不是::value
)
template<typename T>
struct a { static const int value; };
template<> const int a<float>::value = 5;
template<> const int a<double>::value = 14;
template<> const int a<char>::value = 6;
template<> const int a<wchar_t>::value = 33;