Suppose we want to declare a variable of the vector type of STL, and read the information in the file:
Std::ifstream in ("Data.txt");std::vector<int> data (std::istream_iterator<int> (in), STD::ISTREAM_ Iterator<int> ());
After we reference the elements of data, we find that the compiler has an error. Why, let's analyze:
At this point in the compiler, we are actually declaring a function, its return value is a vector, the parameter has two, the first parameter is a Istream_iterator object, the second argument is a parameterless, return istream_iterator function pointer .
This behavior is caused by the compiler mechanism of C + + as far as possible to interpret statements as function declarations.
This is not really a rare phenomenon, such as the following piece of code you may have seen:
Class widget{...}; Inside there is a default constructor widget W ();//The compiler now sees W as a function declaration
One way to solve this problem is to add a parenthesis to the first parameter:
Std::vector<int> Data ((Std::istream_iterator<int> (in)),std::istream_iterator<int> ());
C + + does not allow the shape of a function to participate in parentheses, but allows the function to be enclosed in parentheses. so the compiler confirms that data is a vector object.
Of course, the radical approach is to use temporary variables:
Std::ifstream in ("Data.txt"), Std::istream_iterator databegin (in); Std::istream_iterator Dataend;std::vector<int > Data (databegin,dataend);
This blog content refers to the "effective STL" article 6th.
Declarative issues caused by the parsing mechanism of the C + + compiler