"Immortal Nephi" <Im************@satx.rr.coma écrit dans le message de
news:
1d**********************************...oglegroups.com...
How can I modify member variable inside class if member function has
const like mem_Func(void) const. Please do not offer the keyword --
mutable. I want to know if keyword -- const_cast can be done.
If mutable is only the solution, I will follow not to use const_cast.
Ok it is Evil but you can do it.
struct EvilClass
{
void EvilFunct() const;
int _a;
};
void EvilClass::EvilFunct() const
{
int& tmp = const_cast<int&>(_a);
tmp = 5; // now _a == 5
}
You can also define a template function if you have many variables like
that.
struct EvilClass
{
void EvilFunct() const;
template<typename T>
void EvilSet(T const& val, T const& NewVal) const;
int _a;
};
void EvilClass::EvilFunct() const
{
EvilSet(_a, 5); // much cleaner but maybe also much evil
}
template<typename T>
void EvilClass::EvilSet(T const& val, T const& NewVal) const
{
T& tmp = const_cast<T&>(val);
tmp = NewVal;
}
------------------------
Eric Pruneau