George Kourtis
George Kourtis

Reputation: 2592

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;

Upvotes: 3

Views: 131

Answers (2)

Praetorian
Praetorian

Reputation: 109119

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

Upvotes: 6

Ben Voigt
Ben Voigt

Reputation: 283634

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.

Upvotes: 5

Related Questions