lambda函数抛出错误

Nic*_*Nic 1 c++

我在构建代码时收到此错误消息,

"已指定具有void返回类型的lambda无法返回值"

bool StockCheck::InStock(const Shop& shop) const
{
    return std::any_of(m_products, [&shop, this](const std::unique_ptr<SelectedProduct>& selected)
    {
        auto inStock = selected->ProductInStock(shop);
        return inStock != SelectedProduct::NOT_IN_STOCK && selected->GetProductInStock(code);
    });
}
Run Code Online (Sandbox Code Playgroud)

我正在使用VS2010,这是一个问题吗?这将在VS2013中有效吗?

For*_*veR 6

问题是,你有lambda有两行,编译器无法确定C++ 11中的返回类型(所以它等于void).您可以指定ret.手动输入类似

return std::any_of(m_products.begin(), m_products.end(),
[&shop, this](const std::unique_ptr<SelectedProduct>& selected) -> bool
{
    auto inStock = selected->ProductInStock(shop);
    return inStock != SelectedProduct::NOT_IN_STOCK && selected->GetProductInStock(code);
});
Run Code Online (Sandbox Code Playgroud)

或者inStock只在一行中写入无变量.

return std::any_of(m_products.begin(), m_products.end(),
[&shop, this](const std::unique_ptr<SelectedProduct>& selected)
{
    return selected->ProductInStock(shop) != SelectedProduct::NOT_IN_STOCK &&
    selected->GetProductInStock(code);
});
Run Code Online (Sandbox Code Playgroud)