C++ nested constructor calls vs. function declaration

左心房为你撑大大i 提交于 2019-12-11 01:43:05

问题


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.


回答1:


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(*)(), i.e. 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".




回答2:


This is called most vexing parse :

This snippet :

  input()

could be disambiguated either as

  1. a variable definition for variable class input, taking an anonymous instance of class input or
  2. a function declaration for a function which returns an object of type input and takes a single (unnamed) argument which is a function returning type input (and taking no input).

Most programmers expect the first, but the C++ standard requires it to be interpreted as the second.




回答3:


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.


来源:https://stackoverflow.com/questions/6939986/c-nested-constructor-calls-vs-function-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!