如何在 C++ 标准库类中重载已重载的运算符?

问题描述 投票:0回答:1

我正在尝试实现我自己的矩阵类(二维数组),它使用 [] 运算符来访问其内容,并使用 std::unique_ptr<> 来保存它 - 我知道有更简单的/更好的方法来解决这个问题,但如果可能的话,我想这样做。

我可以为我的类重载 [] 运算符,但不能为 std::unique_ptr 重载,因为它已经这样做了。

matrix m(5,5, 1);     //create a 5x5 matrix filled with 1's
matrix[row];          //this uses my overloaded [] and returns a unique_ptr
matrix[row][column];  //this uses unique_ptr's overloaded [], can't do my own checks

有没有一种优雅的方法来重载此运算符或通过 [] 运算符截取列索引?

我考虑过为 std::unique_ptr<> 创建一个继承自它的包装类,但我更喜欢使用纯类。

c++ operator-overloading smart-pointers
1个回答
0
投票

出于很好的原因,您不能直接执行此操作,但您可以制作一个包装器,使其“外观和感觉”就像您可以为返回的值添加下标一样。我在这里使用 std::array<int,16> 作为矩阵类的替代品。

auto const ptr = std::make_unique<std::array<int,16>>();
At{ptr}[7] = 8;
assert(At{ptr}[7] == 8);

// the following should not compile:
At at{ptr};
at[7] = 12;

这是一个可能的、草拟的实现:

template <typename T> class At { private: T& value; public: At(std::unique_ptr<T> const& ptr) : value{*ptr} {} template <typename I> decltype(auto) operator[](I const i) const&& { return value[i]; } };

请注意,
At::operator[]

仅适用于 const 右值引用,因此强烈建议不要使用左值,并且用户不会试图保留

At
对象。这并不完美,因为如果您真的愿意,您可以找到解决方法。
    

© www.soinside.com 2019 - 2024. All rights reserved.