繁体   English   中英

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

[英]May I use a template for a constant?

我想编写代码如下:

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 ++ 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会遇到解析错误

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

现场演示

适用于所有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 ,这不是标准类型)

它有点笨拙,但有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM