简体   繁体   中英

May I use a template for a constant?

I would like to write code as bellow:

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;

Yes, you can, if your compiler supports the C++1y variable templates feature.

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;

I added spaces between the > and = of the specializations, because clang runs into a parsing error otherwise

error: a space is required between a right angle bracket and an equals sign (use '> =')

Live demo

A solution for all versions of C++ (including before 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;

(Note that the question used wchar , which is not a standard type)

It's a little clumsier, but works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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