简体   繁体   中英

Check if is const on 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_cast ing an object that was declared const

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, eg T** cannot be cast to const T** .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM