【问题标题】:C++: overloading subscript operator (different return typ)C++:重载下标运算符(不同的返回类型)
【发布时间】:2015-11-08 21:09:45
【问题描述】:

我知道返回值不足以覆盖函数(我在stackoverflow上阅读了关于它的不同线程),但是有没有办法重载类的下标运算符,只是为了返回值(我可以'不改为通过引用类型的函数返回)

它必须看起来像或至少像这样工作:

解决此问题的最佳方法是什么(必须是操作员)?

更新: 问题是,不允许仅使用返回类型重载成员或运算符。

struct A {int a; int b; double c;};
struct B {int a; int b; array<double,2> c;};

class Whatever
{
public:
A operator [](unsigned int ) const; //it's just reading the element
B operator [](unsigned int ) const;
}

A operator [](unsigned int Input){
//...
}

B operator [](unsigned int Input){
//...
}

【问题讨论】:

  • 那么您希望它如何工作:std:: cout &lt;&lt; Whatever()[0].a;?您应该能够在某个时候明确指定类
  • 不,我的意思是真正的问题是什么?为什么一定要运营商?
  • 所以您有一些模板代码假定存在operator[],但必须同时适用于AB?如果它是一个模板,它对这两种类型都不起作用吗?我认为您应该发布更多代码,以便我们了解情况的上下文。
  • 它开始看起来像一个典型的 XY 问题...
  • @WilliamKappler 您可以使用带有转换运算符的代理对象来模拟这一点。但是当目标可以接受多种类型时容易混淆,例如std::cout

标签: c++ templates c++11 operator-overloading


【解决方案1】:

假设您知道要访问哪种类型,您可以返回一个转换为任一类型的代理,并且很可能在转换时进行访问。因为您想访问一个应该相当直接的const 对象。尝试对更新界面执行相同操作时,事情会变得更加混乱:

class Whatever;
class Proxy {
    Whatever const* object;
    int             index;
public:
    Proxy(Whatever const* object, int index)
        : object(object)
        , index(index) {
    }
    operator A() const { return this->object->asA(this->index); }
    operator B() const { return this->object->asB(this->index); }
};
class Whatever {
    // ...
public:
    Proxy operator[](int index) { return Proxy(this, index); }
    A asA(index) { ... }
    B asB(index) { ... }
};

主要限制是您不能直接访问AB 的成员:您需要先转换为AB。如果这两种类型实际上是已知的,您可以创建一个Proxy,它会适当地转发相应的成员函数。当然,如果有通常命名的成员函数或数据成员,则需要先显式转换。

【讨论】:

    猜你喜欢
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    相关资源
    最近更新 更多