Const_cast in the template. Is there an unconst modifier?

I have a template class similar to this:

template<T>
class MyClass
{
  T* data;
}

Sometimes I want to use a class with a constant type T as follows:

MyClass<const MyObject> mci;

but I want to change the data with const_cast<MyObject*>data(this is not important why, but the MyClassclass of smart link pointers that stores the link counter in the data itself. MyObjectcomes from some type that contains the counter. Data should not be changed, but the account should be changed smart pointer.).

Is there a way to remove a constant from T? Fictional code:

const_cast<unconst T>(data) 

?

+5
source share
5 answers

- .

, , const_cast, boost remove_const :

template <class T>
struct RemoveConst
{
    typedef T type;
};

template <class T>
struct RemoveConst<const T>
{
    typedef T type;
};

const_cast<typename RemoveConst<T>::type*>(t)->inc();
+11

. const_cast :

char* a;
const char* b;

a = const_cast<char*>(b);
b = const_cast<const char*>(a); // not strictly necessarily, just here for illustration

, mutable? - const.

class foo {
    mutable int x;
public:
    inc_when_const() const { ++x; }
    dec_when_const() const { --x; }
};
+5

, . " ", .. - . , - - .

+4
source

If you can use Boost, the Type Traits library provides a remove_const metafunction that does this.

+3
source

Here is my C ++ 11 function unconst template.

If you use it, you flirt with undefined behavior . You have been warned .

// on Ubuntu (and probably others) compile and test with                                                        
//   g++ -std=c++11 test.c  &&  ./a.out  ;  echo $?                             

template < class T >  T &  unconst  ( T const & t ) {
  return  const_cast < T & >  ( t ) ; 
}

// demonstration of use

struct {
  const int n = 4;
} s;

int main () {
  unconst ( s.n ) = 5;
  return s.n;
}
0
source

All Articles