Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c++ - Why standard container iterators don't overload `->*`?

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

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 << '
'; // This line compiles.

    std::cout << vec.begin()->*mem_ptr << '
'; // This line doesn't compile.
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


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...

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.

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...