我想编写代码如下:
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;
Run Code Online (Sandbox Code Playgroud)
是的,如果编译器支持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;
Run Code Online (Sandbox Code Playgroud)
我在专业化>和=专业化之间添加了空格,因为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;
Run Code Online (Sandbox Code Playgroud)
(注意使用的问题wchar,这不是标准类型)
它有点笨拙,但有效.
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |