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, e.g. T**
cannot be cast to const T**
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With