4

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?

5
  • as simple as template <typename T> using Constant = const T; Commented Dec 17, 2014 at 18:46
  • template <typename T> using Constant = const T; @PiotrS. beat me by 7 sec :( Commented Dec 17, 2014 at 18:46
  • the comments should be answers, also, i dont' quiet remember but is "using" template usage a Cx11 feature? Commented Dec 17, 2014 at 18:49
  • @NickoPo alias templates are available since C++11 Commented Dec 17, 2014 at 18:50
  • Wow, that was much faster than I expected. Commented Dec 17, 2014 at 19:31

2 Answers 2

8

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; 
Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

I was just about to add this to my answer +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.