How do I declare the type of a template constant?

If I do a typedef like

typedef int const cint;

      

cint

will refer to an int which cannot be modified. I can use cint

in any context that accepts a type (template parameter, function definition, etc.).

However, typedefs don't work with templates. I hope you can declare a template, for example Constant<SomeType>

, and refer to const SomeType

how I can do with the cint

above. Is it possible?

+3


source to share


2 answers


C ++ 11:

template <typename T>
using Constant = const T;

Constant<int> i = 1;
//! i = 2; // error: assignment of read-only variable 'i'

      



C ++ 03:

template <typename T>
struct Constant
{
    typedef const T type;
};

Constant<int>::type i = 1;

      

+8


source


std::add_const_t<SomeType>

matches const SomeType

.



+5


source







All Articles