What is the difference between the code snippets labeled "version 1" and "version 2" in the following code section:
int main() {
using namespace std;
typedef istream_iterator<int> input;
// version 1)
//vector<int> v(input(cin), input());
// version 2)
input endofinput;
vector<int> v(input(cin), endofinput);
}
As far as I understand "version 1" is treated as function declaration. But I don't understand why nor what the arguments of the resulting function v
with return type vector<int>
are.
why
Because the Standard says, more or less, that anything that can possibly be interpreted as a function declaration will be, in any context, no matter what.
what the arguments... are
You might not believe this, but it's true. input(cin)
is treated as input cin
; in this spot, parentheses are allowed and simply meaningless. However, input()
is not treated as declaring a parameter of type input
with no name; instead, it is a parameter of type input(*)()
, ie a pointer to a function taking no arguments and returning an input
. The (*) part is unnecessary in declaring the type, apparently. I guess for the same reason that the &
is optional when you use a function name to initialize the function pointer...
Another way to get around this, taking advantage of the fact that we're declaring the values separately anyway to justify skipping the typedef:
istream_iterator<int> start(cin), end;
vector<int> v(start, end);
Another way is to add parentheses in a way that isn't allowed for function declarations:
vector<int> v((input(cin)), input());
For more information, Google "c++ most vexing parse".
This is called most vexing parse :
This snippet :
input()
could be disambiguated either as
Most programmers expect the first, but the C++ standard requires it to be interpreted as the second.
vector<int> v(input(cin), input());
Well, the arguments to this function declaration are these:
input(cin)
- which is an object input (*)()
- which is a pointer to function returning input
and taking no argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.