当 operator* 返回 std::make_pair 时,如何为迭代器重载 operator->

问题描述

给定 auto iterator::operator*() { return std::make_pair(1,2.0); },我可以写出 (*it).first。但是我如何编写 operator-> 使得 it->first 也有效?

Overloading operator-> when operator* returns temporary 适用,因为 std::make_pair 确实返回一个临时值。我当然知道这个简单示例中的类型是 std::pair<int,float>,但通常情况并非如此。链接问题中给出的答案假设您可以拼出类型。

我想出了这个肮脏的黑客:

auto iterator::operator->() {
        auto ptr = new auto(this->operator*());
        return std::unique_ptr<decltype(*ptr)>(ptr);
        // The `decltype` is needed because `unique_ptr` intentionally has no deduction guides
        // it can't distinguish `new` and `new[`]`.

}

这使用了 operator-> 可以转发到另一个类型的事实,正如另一个问题所建议的那样,并且 std::unique_ptr 确实实现了 operator->。我显然不能直接返回 ptr,那会泄漏。但仍然 - 这是一个不必要的堆分配。 N3664 允许它被淘汰,但我宁愿不依赖它。

有没有其他方法可以将 operator-> 写入 operator*,而无需在 operator* 中命名表达式类型?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)