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

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

    Another way could be to write a template that calls the function (using CRTP) and inherit from it.

    template
    struct const_forward {
    protected:
      // forbid deletion through a base-class ptr
      ~const_forward() { }
    
      template
      R *use_const() {
        return const_cast( (static_cast(this)->*pf)() );
      }
    
      template
      R &use_const() {
        return const_cast( (static_cast(this)->*pf)() );
      }
    };
    
    class Bar;
    
    class Foo : public const_forward {
    public:
      const Bar* bar() const { /* code that gets a Bar somewhere */ }
      Bar* bar() { return use_const(); }
    };
    

    Note that the call has no performance lost: Since the member pointer is passed as a template parameter, the call can be inlined as usual.

提交回复
热议问题