Explicit lambda return type

When I try to compile this code (VS2010), I get the following error: error C3499: a lambda that has been specified to have a void return type cannot return a value

 void DataFile::removeComments() { string::const_iterator start, end; boost::regex expression("^\\s?#"); boost::match_results<std::string::const_iterator> what; boost::match_flag_type flags = boost::match_default; // Look for lines that either start with a hash (#) // or have nothing but white-space preceeding the hash symbol remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) { start = line.begin(); end = line.end(); bool temp = boost::regex_search(start, end, what, expression, flags); return temp; }); } 

As I pointed out, lambda has a return type of "void". Moreover, how to indicate that lambda has a return type of "bool"?

UPDATE

The following compilation. Can someone please tell me why this compiles and the other doesn't?

 void DataFile::removeComments() { boost::regex expression("^(\\s+)?#"); boost::match_results<std::string::const_iterator> what; boost::match_flag_type flags = boost::match_default; // Look for lines that either start with a hash (#) // or have nothing but white-space preceeding the hash symbol rawLines.erase(remove_if(rawLines.begin(), rawLines.end(), [&expression, &what, &flags](const string& line) { return boost::regex_search(line.begin(), line.end(), what, expression, flags); })); } 
+51
c ++ lambda c ++ 11 visual-c ++ visual-c ++ - 2012
Mar 08 2018-12-12T00:
source share
3 answers

You can explicitly specify the return type of lambda using -> Type after the argument list:

 []() -> Type { } 

However, if lambda has one statement, and this statement is a return statement (and returns an expression), the compiler can infer the type of the return value from the type of the returned expression. You have several statements in your lambda, so it does not type in.

+121
Mar 08 2018-12-12T00:
source share

The returned lambda type can be inferred, but only if there is only one statement, and this statement is a return that returns an expression (for example, the list of initializers is not an expression). If you have a multi-task lambda, then the return type is considered invalid.

Therefore you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool { start = line.begin(); end = line.end(); bool temp = boost::regex_search(start, end, what, expression, flags); return temp; }) 

But actually your second expression is much readable.

+9
Mar 08 '12 at 16:18
source share

You can have more than one statement when it still returns:

 []() -> your_type {return ( your_statement, even_more_statement = just_add_comma, return_value);} 

http://www.cplusplus.com/doc/tutorial/operators/#comma

+3
Sep 27 '14 at 2:03
source share



All Articles