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

May I use a template for a constant?

本文关键字:常数使 我可以      更新时间:2023-10-16

我想写的代码如下:

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;

可以,如果你的编译器支持c++变量模板特性的话。

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遇到解析错误,否则

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

现场演示

所有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;

(注意问题使用了wchar,它不是标准类型)