Declarative issues caused by the parsing mechanism of the C + + compiler

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.