Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if is const on C++03

Tags:

c++

c++03

How do I check if an object is const without C++11's std::is_const? As far as I know I shouldn't be const_casting an object that was declared const

like image 830
snoopy Avatar asked Nov 20 '12 03:11

snoopy


1 Answers

An example implementation for C++11's is_const is given on cppreference, and it looks like this:

template<class T> struct is_const          : false_type {};
template<class T> struct is_const<const T> : true_type {};

If you put this definition in your C++03 code, you can use is_const there as well, if you add definitions for false_type and true_type (thanks to mfonantini for pointing out the missing true_type and false_type). If you define them as follows, you'll get very close to the definition used in C++11:

struct true_type {
  static const bool value = true;
  typedef bool value_type;
  typedef true_type type;
  operator value_type() const { return value; }
};

struct false_type {
  static const bool value = false;
  typedef bool value_type;
  typedef false_type type;
  operator value_type() const { return value; }
};

The only difference is that the static value is a mere const, not a constexpr, but note that it is a constant expression nevertheless and can be used as template argument. So for all practical purposes, the definition above should work in C++03.

Regarding the last part of your question: There is actually no problem casting a non-const type to const. (Illegal situations can, however, arise with pointers to pointers or references to pointers, e.g. T** cannot be cast to const T**.)

like image 84
jogojapan Avatar answered Oct 04 '22 07:10

jogojapan