为什么标准容器迭代器不会使`-> *`超载? [英] Why standard container iterators don't overload `->*`?

查看:109
本文介绍了为什么标准容器迭代器不会使`-> *`超载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,如果您超载->->*不会自动工作,必须手动进行超载.

Apparently ->* doesn't work automagically if you overload ->, and has to be overloaded manually.

为什么标准容器的迭代器除了->之外不重载->*,从而强制使用(*iter).*mem_ptr而不是iter->*mem_ptr?

Why iterators for standard containers don't overload ->* in addition to ->, forcing usage of (*iter).*mem_ptr instead of iter->*mem_ptr?

#include <iostream>
#include <vector>

struct S
{
    int x;
};

int main()
{
    std::vector<S> vec = {{42}};
    auto mem_ptr = &S::x;

    std::cout << (*vec.begin()).*mem_ptr << '\n'; // This line compiles.

    std::cout << vec.begin()->*mem_ptr << '\n'; // This line doesn't compile.
}

推荐答案

请注意,这些问题通常无法回答,这是operator->*()可能不会超载的一些原因.尽管真正的答案是可能的,但没人会想到它.而且,如果这对您来说是一种重要的缺少语言功能,则您总是可以提交提案.

With the caveat that these questions aren't typically answerable, here are a few reasons why operator->*() may not be overloaded. Although it's possible the real answer is that nobody thought of it. And if this, to you, is an important missing language feature, you could always submit a proposal.

对于初学者来说,ptr->*pmd通常不是一个非常常用的表达方式.因此,您不会写it->*pmd的事实并不是大多数人会错过的,尤其是当(*it).*pmd只需花两个额外字符即可实现完全相同的目标时.这里的潜在上行空间似乎很小.不过,迭代器应与指针保持一致,因此这是有道理的.但是...

For starters, ptr->*pmd just isn't a very commonly used expression in general. So the fact that you cannot write it->*pmd isn't something that most people miss, especially when (*it).*pmd accomplishes exactly the same goal at the cost of just 2 extra characters. The potential upside here seems fairly small. Still, iterators should be consistent with pointers, so it would make sense. But...

指向成员的指针不仅仅是指向成员数据的指针,我们还可以具有指向成员函数的指针,并且可以今天编写(ptr->*pmf)(),其中ptr->*pmf本身是不正确的.使用operator->*根本无法获得这些语义-要使调用操作正常工作,ptr->*pmf必须基本上返回一个lambda.所以现在,这实际上变得相当复杂-除非您只想支持ptr->*pmd.无论采用哪种方法,您都与指针不一致.

Pointers to members aren't just pointers to member data, we can also have pointers to member functions and can write (ptr->*pmf)() today, where ptr->*pmf by itself is ill-formed. You can't get those semantics at all with operator->* - to get the call operation to work, ptr->*pmf would have to basically return a lambda. So now, this actually becomes fairly complicated - unless you want to just support ptr->*pmd. With any approach, you're inconsistent with pointers.

对于输入迭代器,您根本不希望支持operator->*(),因为它将产生立即悬空的引用.

For input iterators, you don't want to support operator->*() at all since it would yield an immediately dangling reference.

对我个人而言,成本(弄清楚如何指定这些运算符,迭代器以及如何处理指向成员函数的指针)似乎并不值得(在一个很少有的表达式中保存2个字符)值得

To me, personally, the cost (figuring out how to specify these operators, for which iterators, and what to do about pointers to member functions) doesn't really seem worth the benefit (saving 2 characters in an expression that's rarely written).

这篇关于为什么标准容器迭代器不会使`-&gt; *`超载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆