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

后端 未结 11 2446
时光取名叫无心
时光取名叫无心 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:46

    Use following trick:

    
    class Bar;
    class Foo {
    public:  
      Bar* bar() { 
        // non-const case
        /* code that does something */ 
      }  
      const Bar* bar() const {    
          return This().bar();  // use non-const case
       }
    
    private:
      //trick: const method returns non-const reference
      Foo & This() const { return const_cast(*this); } 
    };
    

    Note it is possible to use unique function This for any const/non-const functions.

    Alternative solution without static_cast (but I prefer the first one):

    class Bar;
    class Foo {
    public:  
      const Bar* bar() const { /* code that does something */ }  
      Bar* bar() { return const_cast(cthis().bar()); } // use const case
    private:
      const Foo & cthis() const { return *this; } 
    };
    

提交回复
热议问题