Lambda的显式返回类型 [英] Explicit Return Type of Lambda
问题描述
当我尝试编译此代码(VS2010)时,出现以下错误:
error C3499: a lambda that has been specified to have a void return type cannot return a value
When I try and compile this code (VS2010) I am getting 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;
});
}
我如何指定lambda具有'void'返回类型.此外,如何指定lambda具有布尔"返回类型?
How did I specify that the lambda has a 'void' return type. More-over, how do I specify that the lambda has 'bool' return type?
更新
以下编译.有人可以告诉我为什么编译而另一个不编译吗?
The following compiles. Can someone please tell me why that compiles and the other does not?
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); }));
}
推荐答案
您可以在参数列表后使用-> Type
显式指定lambda的返回类型:
You can explicitly specify the return type of a lambda by using -> Type
after the arguments list:
[]() -> Type { }
但是,如果一个lambda有一个语句,而该语句是一个return语句(并且它返回一个表达式),则编译器可以从该一个返回表达式的类型中推断出返回类型.您的lambda中有多个语句,因此不会推断出类型.
However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.
这篇关于Lambda的显式返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!