如何从const方法生成非const方法? [英] How to generate a non-const method from a const method?

查看:130
本文介绍了如何从const方法生成非const方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在争取const正确性的同时,我经常发现自己在编写这样的代码

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 a Bar somewhere */ }

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

用于许多方法,例如 bar() 。编写这些手工调用const的非const方法很繁琐。此外,我感觉自己在重复自己–这让我感到难过。

for lots of methods like bar(). Writing these non-const methods which call the const ones by hand is tedious; besides, I feel I am repeating myself – which makes me feel bad.

我该怎么做才能减轻这项任务? (不允许使用宏和代码生成器。)

What can I do to alleviate this task? (Macros and code generators are not allowed.)

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

Besides litb's solution I also like my own. :)

推荐答案

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

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

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>(); }
};

请注意,调用没有性能损失:由于成员指针作为模板参数传递,因此通话可以照常内联。

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.

这篇关于如何从const方法生成非const方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆