C++:重载下标运算符(不同的返回类型)

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

我知道返回值不足以覆盖函数(我在 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){
//...
}

最佳答案

假设您知道要访问哪种类型,您可以返回一个代理,该代理可以转换为任何一种类型,并且很可能在转换时进行访问。由于您想要访问一个应该相当简单的 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 的成员:您需要转换为A 或a B 首先。如果这两种类型实际上是已知的,您可以创建一个 Proxy 来适本地转发相应的成员函数。当然,如果有共同命名的成员函数或数据成员,您需要先显式转换。

关于C++:重载下标运算符(不同的返回类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33599075/

相关文章:

c++ - 无限大小的整数?

C++ SWAP 函数什么都不做?

c++了解模板,类型名称的语法

c++ - 为什么我会收到 Unresolved external 问题?

c++ - ConcRT 同步结构与标准库

c++ - std::unordered_map 的哈希值

c++ - 为什么 const_cast away volatile 只适用于指针

c++ - 从起点遍历图形并在起点结束 C++

c++ - `typedef typename Foo<T>::Bar Bar'的模板声明

c++ - 如何在通用 lambda 中完美转发 `auto&&`?