公共/受保护访问的基于const的函数重载

时间:2014-02-27 17:45:16

标签: c++ c++11 const overloading access-specifier

(我相信)我知道基于常量重载函数:如果瞬间是const,则调用const方法,否则调用非常量方法。

示例(也在ideone):

#include <iostream>

struct S
{
  void print() const { std::cout << "const method" <<std::endl };
  void print()       { std::cout << "non-const method" <<std::endl };
};

int main()
{
  S const s1;
  s1.print(); // prints "const method"
  S s2;
  s2.print(); // prints "non-const method"
  return 0;
};

我尝试/尝试在我的代码中使用它,但在const重载方法没有相同的访问类别时遇到了一些问题。它可能是糟糕的样式,但这里有一个示例反映了返回引用以避免复制并使用const来限制意外更改的想法:

struct Color;
struct Shape
{
  double area;
};

class Geometry
{
public:
  // everybody can alter the color of the geometry, so 
  // they get a mutable reference
  Color& color() { return m_color; };

  // not everybody can alter the shape of the Geometry, so
  // they get a constant reference to the shape.
  Shape const& shape() const { return m_shape; };

protected:
  // derived classes can alter the shape, so they get 
  // access to the mutable reference to alter the shape.
  Shape & shape() { return m_shape; };

private:
  Shape m_shape;
  Color m_color;
};

我现在面临的问题是,我希望编译器选择公共的,const - 返回形状函数,如果其他函数与几何图形混淆,请说按它们的区域着色,这样就可以了需要访问几何的形状:

// this one fails
void colorByArea() {
  for( Geometry g : geometryList )
  { g.color() = colorMap[g.shape().area]; }
}

// this one is a clunky workaround
void colorByArea() {
  for( Geometry g : geometryList )
  { 
    Geometry const& g_const = g;
    g.color() = colorMap[g_const.shape().area];
  }
}

这(或类似的东西)失败,出现以下明显可理解的错误:

‘Shape& Geometry::shape()’ is protected 
  Shape & shape() { return m_shape; };

^ error: within this context
  g.color() = colorMap[g.shape().area];

(我在ideone处设置了一个略微简化的非编译示例。)

我得到(在一定程度上)为什么会发生这种情况:g不是const,因此可以调用非const形状(),即protectec,但是显然失败了。

所以我想我的问题是: 如果无法访问非const函数,有没有办法让某种“回退”到const函数?

2 个答案:

答案 0 :(得分:1)

  

如果无法访问非const函数,有没有办法让某种“回退”到const函数?

没有;在访问检查之前发生重载解析。

这不仅仅是糟糕的风格;这是糟糕的设计。公共getter函数与受保护函数在概念上是不同的,它允许具有内部知识的代码修改对象的内部状态。通常,这两个函数甚至不需要具有相关的返回类型。因此,它们不应该有相同的名称。

答案 1 :(得分:0)

您可以使用const_cast来允许将const版本调用为:

int main()
{
  S s2;
  const_cast<const S&>(s2).print(); // prints "const method"
  return 0;
};

但重命名其中一种方法会更好/更简单。