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.
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.
You might not believe this, but it’s true.
input(cin)is treated asinput cin; in this spot, parentheses are allowed and simply meaningless. However,input()is not treated as declaring a parameter of typeinputwith no name; instead, it is a parameter of typeinput(*)(), i.e. a pointer to a function taking no arguments and returning aninput. 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:
Another way is to add parentheses in a way that isn’t allowed for function declarations:
For more information, Google “c++ most vexing parse”.