Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: expected initializer before ‘:’ token

Tags:

c++

linux

porting

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

I have this snippet of code,

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

that I cannot compile because of this error:

CNWController.cpp:154: error: expected initializer before ‘:’ token

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

like image 733
Aslan986 Avatar asked May 02 '13 15:05

Aslan986


1 Answers

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 you to explicitly request C++11 support, by giving the command-line option -std=c++11, or c++0x on compilers as old as yours.

If you can't upgrade, then you'll 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 (as long as you enable C++0x support), to save you writing std::vector<string>::const_iterator.

If you really do need a non-const reference to the vector's elements then, whichever style of loop you use, you'll need to remove the const from the function parameter.

like image 95
Mike Seymour Avatar answered Sep 29 '22 19:09

Mike Seymour