c++ - 如何从 const 方法生成非常量方法?

标签 c++ dry const-correctness

在努力实现 const 正确性的同时,我经常发现自己编写了这样的代码

class Bar;

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

  Bar* bar() {
    return const_cast< Bar* >(
      static_cast< const Foo* >(this)->bar());
  }
};

用于许多方法,例如 bar()。编写这些手动调用常量方法的非常量方法是乏味的;此外,我觉得我在重复自己——这让我感觉很糟糕。

我可以做些什么来减轻这个任务? (不允许使用宏和代码生成器。)

编辑:除了 litb 的解决方案外,我也喜欢我自己的解决方案。 :)

最佳答案

另一种方法是编写一个调用函数(使用 CRTP)并从中继承的模板。

template<typename D>
struct const_forward {
protected:
  // forbid deletion through a base-class ptr
  ~const_forward() { }

  template<typename R, R const*(D::*pf)()const>
  R *use_const() {
    return const_cast<R *>( (static_cast<D const*>(this)->*pf)() );
  }

  template<typename R, R const&(D::*pf)()const>
  R &use_const() {
    return const_cast<R &>( (static_cast<D const*>(this)->*pf)() );
  }
};

class Bar;

class Foo : public const_forward<Foo> {
public:
  const Bar* bar() const { /* code that gets a Bar somewhere */ }
  Bar* bar() { return use_const<Bar, &Foo::bar>(); }
};

请注意,调用没有性能损失:由于成员指针作为模板参数传递,调用可以像往常一样内联。

关于c++ - 如何从 const 方法生成非常量方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1333849/

相关文章:

c++ - 如何有效地将 git 存储库/子模块用于具有许多依赖项的 C++ 产品?

c# - 如何在 C# 中创建未转义的十六进制字节字符串

ios - 我怎样才能在一个额外的功能中外包这种重复的代码味道? iOS Swift 函数

c++ - 在 const 方法中使用引用

c++ - 容器的 const_casting 元素类型

c++ - 在 C++ 中创建 Xml 字符串

c++ - 有没有办法重复一个循环周期?

c# - 如何管理装饰 ApiController 中的重复?

javascript - 如何在 Javascript 中正确使用 mixins

c++ - 使用 C 库时 C++ 中的常量正确性