A two-parameter vector constructor is parsed as a function declaration

Consider the following example:

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

int main()
{
    std::string sen = "abc def ghi jkl";
    std::istringstream iss(sen);

    std::vector<std::string>    // declaration in question
    vec(std::istream_iterator<std::string>(iss),
        std::istream_iterator<std::string>());

    std::copy(vec.begin(), vec.end(),
              std::ostream_iterator<std::string>(std::cout, "\n"));
}

The compiler throws an error when called std::copy

request for member 'begin' in 'vec', which is of non-class type...

I can get around the error, for example:

std::istream_iterator<std::string> it_begin(iss);
std::istream_iterator<std::string> it_end;
std::vector<std::string> vec(it_begin, it_end);

or by placing parentheses around each parameter, for example:

std::vector<std::string>
vec((std::istream_iterator<std::string>(iss)),
    (std::istream_iterator<std::string>()));

or even with the new uniform initialization in C ++ 11:

std::vector<std::string> vec { /*begin*/, /*end*/ };

Why does the compiler parse the declaration in the example as a function declaration? I know about the most unpleasant analysis, but I thought this only happened with empty parameter lists. I also wonder why the second workaround works.

+5
source share
1 answer

This is still the most annoying parsing.

std::vector<std::string>                     // return type
vec(                                         // function name
    std::istream_iterator<std::string>(iss), // param 1: an iterator called (iss), or just iss
    std::istream_iterator<std::string>()     // param 2: unnamed function 
);                                           //          returning iterator

geordi says:

<tomalak> << ETYPE_DESC(vec); std::vector<std::string> vec(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>());
<geordi> lvalue function taking a istream_iterator<string, char, char_traits<char>, long> , a pointer to a nullary function returning a istream_iterator<string, char, char_traits<char>, long> , and returning a vector of strings

, (.. iss(iss)) . .

, , , (, , ) , .


, :

void foo(int (x)) {
   cout << x;
}

int main() {
   foo(42);
}

42.

+9

All Articles