Error: expected initializer before ': token

I am trying to compile C ++ code (which can be compiled using Visual Studio 2012 on Windows) with g++-4.4 .

I have this piece of code,

 const std::string cnw::restoreSession(const std::vector<string> &inNwsFile) { for (std::string &nwFile : inNwsFile){ // some... } } 

which I cannot compile due to this error:

 CNWController.cpp:154: error: expected initializer before ':' token 

Can you give me some tips on how to solve this problem?

+4
source share
1 answer

Your compiler is too old to support range-based for syntax. According to GNU , it was first supported in GCC 4.6. GCC also requires that you explicitly request C ++ 11 support by providing the -std=c++11 or c++0x command-line -std=c++11 to compilers as old as yours.

If you cannot upgrade, you will need the old school equivalent:

 for (auto it = inNwsFile.begin(); it != inNwsFile.end(); ++it) { std::string const &nwFile = *it; // const needed because inNwsFile is const //some... } 

I believe auto is available in GCC 4.4 (if you enable C ++ 0x support) to save the std::vector<string>::const_iterator entry.

If you really need a const reference to vector elements, then whatever style of the loop you use, you need to remove the const from the function parameter.

+12
source

All Articles