Explicit Return Type of Lambda

后端 未结 3 1662
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 23:38

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 va

相关标签:
3条回答
  • 2020-12-01 00:10

    You can have more than one statement when still return:

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

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

    0 讨论(0)
  • 2020-12-01 00:14

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

    []() -> Type { }
    

    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.

    0 讨论(0)
  • 2020-12-01 00:35

    The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

    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 really, your second expression is a lot more readable.

    0 讨论(0)
提交回复
热议问题