How to generate a non-const method from a const method?

后端 未结 11 2435
时光取名叫无心
时光取名叫无心 2021-02-08 11:18

While striving for const-correctness, I often find myself writing code such as this

class Bar;

class Foo {
public:
  const Bar* bar() const { /* code that gets          


        
11条回答
  •  隐瞒了意图╮
    2021-02-08 11:34

    The answer I came up with myself after bending my mind a bit. However, I think I can improve it using the ideas from litb's answer, which I'll post later. So my solution so far looks like this:

    class ConstOverloadAdapter {
    protected:
    
      // methods returning pointers 
    
      template< 
        typename R, 
        typename T >
      R* ConstOverload(
        const R* (T::*mf)(void) const) {
          return const_cast< R* >(
            (static_cast< const T* >(this)->*mf)());
        }
    
      // and similar templates for methods with parameters 
      // and/or returning references or void
    };
    
    class Bar;
    
    class Foo : public ConstOverloadAdapter {
    public:
      const Bar* bar() const { 
        /* implementation */ }
    
      Bar* bar(void* = 0) {  // the dummy void* is only needed for msvc
                             // since it cannot distinguish method overloads
                             // based on cv-type. Not needed for gcc or comeau.
        return ConstOverload(&Foo::bar); }
    };
    

提交回复
热议问题