`

Watch out the parsing mechanism of C++ compiler

    博客分类:
  • C++
阅读更多

From the book named <<Effective STL 50 Specific Ways to Improve Your Use of the Standard Template Library>>, I knew the suggestion of " Watch out the parsing mechanism of C++ compiler", which is the sixth suggestion in that book. This fact is because of C++ using the strategy of "interpreted as being function as possible".

     There is a classic and typical example about reading data from a file and using the data as parameters to construct a list.

The code is below:

   

#include <iostream>
#include <fstream>
#include <list>
#include <iterator>
using namespace std;

int main(int argc, char* argv[])
{

	std::ifstream dataFile( "Test.txt" ); 

	std::list< int > intData( std::istream_iterator< int >( dataFile ), 

                        std::istream_iterator< int >() ); 

	std::list< int >::iterator iter = intData.begin();
	
	for(iter; iter != intData.end(); ++iter)
	{
		std::cout<<*iter<<std::endl;
	}
	return 0;
}

 

 

If you use this code compiled with gcc 4.4.7, you will get below output:

parseMech.cc:19: error: request for member ‘begin’ in ‘intData’, which is of non-class type ‘std::list<int, std::allocator<int> >(std::istream_iterator<int, char, std::char_traits<char>, int>, std::istream_iterator<int, char, std::char_traits<char>, int> (*)())’

 It says we are using a non-class type, which means what we want to construct a list above is not valid.

So It's important for us to explore how the compiler deals with the statement of definition of the variable iniData. Here C++ Compiler uses the strategy which introduced above to interpret the definition as a declaration of a function. It treats the dataFile as a parameter with type of std::istream_iterator<int> and treats the std::istream_iterator<int>() as a function pointer which points to a function having no parameter and return type of std::istream_iteratior<int>.

 

Now we know what the C++ Compiler actually do , then what we can do to avoid this mechanism of C++ Compiler?

 

There are two solutions to solve this problem:

1. wrapped the std::istream_iterator<int>(dataFile) with pair of parentheses. the result is

#include <iostream>
#include <fstream>
#include <list>
#include <iterator>
using namespace std;

int main(int argc, char* argv[])
{

	std::ifstream dataFile( "Test.txt" ); 

  

	std::list< int > intData(( std::istream_iterator< int >( dataFile )), 

                        std::istream_iterator< int >() ); 


	std::list< int >::iterator iter = intData.begin();
	
	for(iter; iter != intData.end(); ++iter)
	{
		std::cout<<*iter<<std::endl;
	}
	return 0;
}

 

Then we re-compile this code and the damn error would be gone.  But unfortunately, this solution is not well supported by all of compilers. So We will introduce the other solution.

 

2. The better solution is to avoid using anonymous object, the following code would always work correctly:

#include <fstream>
#include <list>
#include <iterator>
using namespace std;

int main(int argc, char* argv[])
{

	std::ifstream dataFile( "Test.txt" ); 

  	std::istream_iterator< int > dataBegin(dataFile);
  	 
  	std::istream_iterator< int > dataEnd;

	std::list< int > intData(dataBegin, dataEnd ); 

	std::list< int >::iterator iter = intData.begin();
	
	for(iter; iter != intData.end(); ++iter)
	{
		std::cout<<*iter<<std::endl;
	}
	return 0;
}

 Here we explicitly declare the dataBegin and dataEnd.

 

分享到:
评论

相关推荐

    The Theory of Parsing, Translation, and Compiling

    Aho and Ullman - The Theory of Parsing, Translation, and Compiling - Vol. 1 (1972).djvu Aho and Ullman - The Theory of Parsing, Translation, and Compiling - Vol. 2 (1973).djvu

    acpi控制笔记本风扇转速

    Enhanced the implementation of the "serialized mode" of the interpreter (enabled via the AcpiGbl_AllMethodsSerialized flag.) When this mode is specified, instead of creating a serialization semaphore ...

    Modern Compiler Implementation in C

    This new, expanded textbook describes all phases of a modern compiler: lexical analysis, parsing, abstract syntax, semantic actions, intermediate representations, instruction selection via tree ...

    Morgan Kaufmann - Engineering A Compiler

    The proliferation of processors, environments, and constraints on systems has cast compiler technology into a wider variety of settings, changing the compiler and compiler writer's role. No longer is ...

    sdilreade(Parsing the IL of a Method Body)

    how to get a readable and programmable result from the IL array provided by the MethodBody.GetILAsByteArray() method.

    C++ parsing DSL.zip

    C++ parsing DSL

    Bloodshed Dev-C++

    * Added the possibility to modify the value of a variable during debugging (right click on a watch variable and select "Modify value") * During Dev-C++ First Time COnfiguration window, users can now ...

    The YARD Parsing Framework for C++-开源

    YARD C ++解析框架现在托管在http://code.google.com/p/yardparser/上。

    Parsing JSON in Swift

    Parsing JSON in Swift will teach you to harness the power of Swift and give you confidence that your app can gracefully handle any JSON that comes its way. You'll learn: - How to use ...

    Crafting a Compiler by Charles N. Fisher Richard J. LeBlanc 带目录版

    2.1 An Informal Definition of the ac Language 32 2.2 Formal Definition of ac 33 2.2.1 Syntax Specification 33 2.2.2 Token Specification 36 2.3 Phases of a Simple Compiler 37 2.4 Scanning 38 2.5 ...

    Parsing_with_Perl_6_Regexes_and_Grammars.pdf

    You’ll see how regexes are used for searching, parsing, and validation: in particular the grammar extension makes them uniquely suitable for parsing, the main focus of this book. Written by Perl 6 ...

    现代编译原理-Java语言描述

    The new, expanded version of this textbook describes all phases of a modern compiler: lexical analysis, parsing, abstract syntax, semantic actions, intermediate representations, instruction selection...

    Dependency Parsing

    Dependency Parsing Dependency Parsing Dependency Parsing

    parsing algorithm

    This parsing is for parsing all the node in one sentence.

    Trends in Parsing Technology

    Parsing Technology 趋势!

    VAX v10.8.2029

    Fixed parsing of C++ rvalue references and improved parsing of decltypes. (case=20625) Fixed coloring of variables named "value." (case=37888) Fixed parsing of C++11 member initializations. (case=...

    A JSON parser in C++

    Perhaps because web service clients are usually written in dynamic languages these days, none of the existing C++ JSON parsers fitted my needs very well, so I wrote one that I used in another project....

    Qt5.Cplusplus.GUI.Programming.Cookbook.1783280271

    Therefore, improving the visual quality of your application is vital in order to overcome the market competition and stand out from the crowd. This book will teach you how to develop functional and ...

    Parsing Techniques: A Practical Guide (Monographs in Computer Science)

    This second edition of Grune and Jacobs’ brilliant work presents new developments and discoveries that have been made in the field. Parsing, also referred to as syntax analysis, has been and ...

Global site tag (gtag.js) - Google Analytics