从const调用nonconst成员版本 [英] Call nonconst member version from const

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

问题描述


可能重复:

我有两个成员

A &B::GetA (int i)
{
    return *(m_C[m_AtoC[i]]);
}

const A &B::GetA (int i) const
{
    return *(m_C[m_AtoC[i]]);
}

现在我只是重复代码,但可能存在很好的方法它。我真的不想处理类型转换从const到非const。

for now i just duplicate code, but may be there exists nice way to do it. I certanly dont want to deal with type cast from const to non-const.

编辑:所以我想调用一个成员frm另一个避免代码重复。 >

So i want to call one member frm another to avoid code duplication.

推荐答案

[注意纠正; )

[Note the correction; sorry for getting it the wrong way round initially.]

这是使用 const_cast ,并且它允许通过将非const函数的调用转发到相应的const函数来执行重复数据删除代码:

This is an appropriate situation for using a const_cast, and it allows you to deduplicate code by forwarding the call from the non-const function to the corresponding const function:

A & B::GetA(int index) 
{
    return const_cast<A &>(static_cast<B const *>(this)->GetA(index));
}

重要的是要注意,这只能在一个方向:实现非常量方法的常量,但不是其他方式round:常量调用 GetA()获得对所涉及对象的常量引用,但由于我们有额外的信息,它实际上确定要突变的对象,我们可以安全地丢弃的结果的常量。

It's important to note that this should only be done in one direction: You can implement the non-const method in terms of the constant one, but not the other way round: The constant call to GetA() gets a constant reference to the object in question, but since we have additional information that it's actually OK to mutate the object, we can safely cast away the constness from the result.

在Scott Meyer的 Effective C ++ 中甚至还有一章关于这个技术。

There's even a chapter on precisely this technique in Scott Meyer's Effective C++.

这篇关于从const调用nonconst成员版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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