Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const overloading without having to write function twice [duplicate]

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).

like image 374
Unimportant Avatar asked Jul 25 '12 18:07

Unimportant


2 Answers

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)
like image 154
Ben Voigt Avatar answered Sep 20 '22 13:09

Ben Voigt


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();
  }
}
like image 44
Roman R. Avatar answered Sep 18 '22 13:09

Roman R.