const overloading without having to write function twice
c++, constants, overloading
Solution
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)
Problem
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).