开发者

C++ nested constructor calls vs. function declaration

What is the difference between t开发者_JAVA百科he 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(*)(), 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".


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜