我可以为常量使用模板吗?

3
我希望写出以下代码:

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;
2个回答

6

如果您的编译器支持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;

我在特化模板参数时,在>=之间添加了空格,因为否则clang会出现解析错误。

错误:右尖括号和等号之间需要一个空格(使用'> =')

在线演示


他不希望常量的类型随类型参数而变化。template<> const bool a<bool> = 17; 是行不通的,而 template<> const int a<bool> = 17; 应该可以。 - Ben Voigt
但是我需要所有这些常量都是相同类型,即int。上面的语法是否实现了这一点?我检查了代码,最后两个打印出来的是字符。所以这不是我需要的。有没有办法实现其他行为? - George Kourtis
@GeorgeKourtis 我误解了你的意图。已更新答案。 - Praetorian
@GeorgeKourtis 不要依赖于 typeid - Shoe
@Praetorian,使用GNU G++似乎无法正常工作。我有其他选择吗? - George Kourtis
显示剩余3条评论

5

适用于所有版本的C++(包括C++11之前)的解决方案:

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;

(请注意,该问题使用了非标准类型)
这有点笨拙,但是可以运行。

我知道那个解决方案,但我更喜欢你之前发布的另一个。所以似乎只有宏才能解决这个问题? - George Kourtis
@GeorgeKourtis:既然Praetorian已经修复了代码(据我所知,它与您的问题中的代码完全相同,只是添加了一个默认值),那就接受他的答案吧。 - Ben Voigt
constexpr 函数也可以工作,调用时的行噪声会少一些(只需使用 () 而不是 ::value)。 - Ben Voigt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接