Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a template constant type?

If I make a typedef such as

typedef int const cint;

cint will refer to an int that can't be modified. I can use cint in any context that takes a type (template parameter, function definition, etc).

However, typedefs don't work with templates. My hope is to be able to declare a template like Constant<SomeType> and have this refer to a const SomeType, the way I can do with cint above. Is it possible?

like image 252
Kian Avatar asked Dec 12 '22 02:12

Kian


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;
like image 181
Piotr Skotnicki Avatar answered Dec 13 '22 17:12

Piotr Skotnicki


std::add_const_t<SomeType> is the same as const SomeType.

like image 24
aschepler Avatar answered Dec 13 '22 16:12

aschepler