C++:重载下标运算符(不同的返回类型)
C++: overloading subscript operator (different return typ)
我知道一个返回值不足以覆盖一个函数(我在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) { ... }
};
主要的限制是不能直接访问A
和B
的成员:需要先转换为A
或B
。如果这两种类型实际上是已知的,那么可以创建一个Proxy
,它适当地转发各自的成员函数。当然,如果有常用的命名成员函数或数据成员,则需要首先显式转换。
相关文章:
- 为什么重载运算符可以返回其返回类型以外的其他内容?
- 重载函数仅在返回类型上有所不同
- boost::enable_if on 成员函数,重载返回类型
- clang 拒绝具有尾随 decltype 返回类型的模板调用是否正确,具体取决于其重载之一?
- 按返回类型重载函数模板
- 为什么在下面的代码返回类型中是用于运营商重载的类类型
- 具有多重继承的纯虚函数重载和协变返回类型
- 如何使用内置返回类型重载运算符?
- 同时使用参数重载和返回类型重载
- 为什么+运算符重载返回类型是类类型而不是整数
- 重载参数类型和返回类型上的函数
- 错误-仅返回类型不同的函数不能重载.c++
- 重载运算符:常量与非常量返回类型:任何性能差异
- 可以使用尾随返回类型的条件重载
- 按返回类型重载模板
- 按返回类型重载
- C++按返回类型重载函数
- 使用专门的模板根据返回类型重载函数
- 我是否可以使用不同的返回类型重载"运算符新"?
- 函数映射容器中C++函数返回类型重载:自动推导失败,并出现编译器错误