简体   繁体   中英

lambda function throwing error

I am getting this error message when I build my code,

"a lambda that has been specified to have a void return type cannot return a value"

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);
    });
}

I am using VS2010, is it a problem? This will work in VS2013?

Problem is, that you have lambda with two lines and compiler cannot determine return type (so it's equal to void) in C++11. You can specify ret. type manually like

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);
});

or write without variable inStock just in one line.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM