开发者

C++0x lambda return value type-inferencing rules

Consider the two lambda functions in the following VC++ 10.0 code:

template <typename T>
void eq(uint fieldno, T value) {
    table* index_table = db.get_index_table(fieldno);
开发者_如何转开发    if (index_table == nullptr) return;
    std::set<uint> recs;
    index_table->scan_index<T>(value, [&](uint recno, T n)->bool {
        if (n != value) return false;
        recs.insert(recno);
        return true;
    });
    add_scalar_hits(fieldno, recs).is_hit =
        [=](tools::wsdb::field_instance_t& inst) {
            return boost::get<T>(inst) == value;
        };
}

In the first lambda function, I was forced to use the ->bool return type specification whereas in the second lambda the compiler was perfectly happy to infer the return type.

My question is: when can the compiler infer the return type on a lambda? Is it only when you have a simple one-liner?


"Is it only when you have a simple one-liner?"

Yes. According to the latest public C++0x draft (§5.1.2/4),

If a lambda-expression does not include a trailing-return-type, it is as if the trailing-return-type denotes the following type:

  • if the compound-statement is of the form

    { return attribute-specifieropt expression ; }

    the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conver- sion (4.2), and function-to-pointer conversion (4.3);

  • otherwise, void.

[ Example:

 auto x1 = [](int i){ return i; }; // OK: return type is int
 auto x2 = []{ return { 1, 2 }; }; // error: the return type is void (a
                                   // braced-init-list is not an expression)

end example ]

Therefore, your first lambda expression is interpreted as returning void, which is not right, so you need to add a -> bool to explicitly specify the return type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜