Reputation: 4982
I have a template class like this:
template<T>
class MyClass
{
T* data;
}
Sometimes, I want to use the class with a constant type T as follows:
MyClass<const MyObject> mci;
but I want to modify the data using const_cast<MyObject*>data
(it is not important why but MyClass
is a reference count smart pointer class which keeps the reference count in the data itself. MyObject
is derived from some type which contains the count.
The data should not be modified but the count must be modified by the smart pointer.).
Is there a way to remove const-ness from T
? Fictional code:
const_cast<unconst T>(data)
?
Upvotes: 9
Views: 10278
Reputation: 1482
Here is my C++11 unconst
function template
.
If you use it, you are flirting 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;
}
Upvotes: 0
Reputation: 41351
The simplest way here would be to make the reference count mutable.
However, if you are interested in how it would work with the const_cast
, then reimplementing boost's remove_const
should be quite simple:
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();
Upvotes: 15
Reputation: 490663
Make the reference count mutable in the class managed by your intrusive pointer. This is entirely reasonable, and reflects "logical constness" exactly correctly -- i.e. changing the object's reference count does not reflect any change in the state of the object itself. In other words, the reference count isn't logically part of the object -- the object just happens to be a convenient place to store this semi-unrelated data.
Upvotes: 4
Reputation: 7388
If you can use Boost, the Type Traits library provides the remove_const metafunction that does that.
Upvotes: 3
Reputation: 18984
You have the answer. const_cast works in both directions:
char* a;
const char* b;
a = const_cast<char*>(b);
b = const_cast<const char*>(a); // not strictly necessarily, just here for illustration
As for you specific issue, have you considered the mutable keyword? It allows a member variable to be modified inside a const method.
class foo {
mutable int x;
public:
inc_when_const() const { ++x; }
dec_when_const() const { --x; }
};
Upvotes: 7