c++declarationfunction-declarationambiguity

Why were parentheses disambiguated as a function declaration with std::istream_iterator?


auto queue = [](string str) {
    istringstream ss(str);
    //std::copy(std::istream_iterator<string>(ss),
    //          std::istream_iterator<string>(),
    //          std::ostream_iterator<string>(std::cout, " "));

    //deque<string> q(std::istream_iterator<string>(ss), std::istream_iterator<string>{});
    deque<string> q(std::istream_iterator<string>(ss), std::istream_iterator<string>());
    return q;
};

Why would the compiler complain

parentheses were disambiguated as a function declaration [-Wvexing-parse]

if I construct a container with istream_iterator<string>().

Is there any difference with parameters in std::copy and container constructor?


Solution

  • This line

     deque<string> q(std::istream_iterator<string>(ss),
                     std::istream_iterator<string>());
    

    is a function declaration with the return type deque<string> and two parameters of the type std::istream_iterator<string>. The first parameter has the name ss and the second parameter is unnamed.

    To make this line a declaration of the variable q you should write either

     deque<string> q( ( std::istream_iterator<string>(ss) ),
                      (  std::istream_iterator<string>() ) );
    

    or

     deque<string> q(std::istream_iterator<string>{ ss },
                     std::istream_iterator<string>{});
    

    In this case there are used expressions instead of parameter declarations.

    You may include declarators in parentheses. For example

    int ( x );
    

    When a declaration is a parameter declaration then you may omit a declarator like

    int()
    

    Here is an example of three declarations of the same function.

    int f( int( x ) );
    int f( int x );
    int f( int( x ) )
    {
        return 2 * x;
    }