Possible Duplicate:
Elegant solution to duplicate, const and non-const, getters?
Say I have a c++ class with a memberfunction which is overloaded for const, like this:
Type* DoSomething();
const Type* DoSomething() const;
If this is a larger, more complex member, how does one prevent having to write the same code twice ? Can't call any non-const functions from the const one. And calling the const version from the non-const one results in a const pointer wich has to be cast to non-const (wich smells a bit imo).
You can delegate to a template static member function, as in:
class Widget
{
Type member;
template<typename Result, typename T>
static Result DoSomethingImpl(T This)
{
// all the complexity sits here, calculating offsets into an array, etc
return &This->member;
}
public:
Type* DoSomething() { return DoSomethingImpl<Type*>(this); }
const Type* DoSomething() const { return DoSomethingImpl<const Type*>(this); }
};
In C++11, you can even get rid of the non-inferred template argument, with:
static auto DoSomethingImpl(T This) -> decltype(This->member)
You did it once, and to do it second time with a const attribute on the class, you can use const_cast
:
class Foo
{
Type* DoSomething()
{
// Lots of stuff
}
const Type* DoSomething() const
{
return const_cast<Foo*>(this)->DoSomething();
}
}
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