Reputation: 1364
I have a template class, called OneCell
, here the definition:
template <class T>
class OneCell
{
.....
}
I have a cast operator from OneCell
to T, here
operator T() const
{
getterCount++;
return value;
}
As you see, I want to increment variable in this method, but i get an error because the keyword const
.
On the other hand, if I remove this keyword, the casting doesn't work at all.
What can I do?
Thank you, and sorry about my poor English.
Upvotes: 0
Views: 118
Reputation: 361762
Actually operator T() const
is a const-member function, inside which this
pointer refers to a const
object, which in turns makes the getterCount const
as well.
The solution is to declare getterCount
as mutable, as shown below:
mutable size_t getterCount;
Now getterCount
can be incremented in const member function, which also means, it can be incremented even if the object is const
:
void f(OneCell const & cell)
{
//incrementing getterCount!
++cell.getterCount; //ok, even though cell is const!
}
Upvotes: 5
Reputation: 81399
As you see, I want to increment variable in this method, but i get an error because the keyword const. On the other hand, if I remove this keyword, the casting doesn't work at all.
It will work, but only on mutable instances of OneCell
.
What can I do?
Go mutable
, assuming that you change the bitwise constness but not the logical constness.
mutable int getterCount;
Upvotes: 3