如何将 [[nodiscard]] 属性应用于 lambda?

问题描述 投票:0回答:2

我想防止人们在不处理返回值的情况下调用 lambda。

Clang 4.0 拒绝我尝试过的一切,使用 -std=c++1z 进行编译:

auto x = [&] [[nodiscard]] () { return 1; };
// error: nodiscard attribute cannot be applied to types
auto x = [[nodiscard]] [&]() { return 1; };
// error: expected variable name or 'this' in lambda capture list
auto x [[nodiscard]] = [&]() { return 1; };
// warning: nodiscard attribute only applies to functions, methods, enums, and classes
[[nodiscard]] auto x = [&]() { return 1; };
// warning: nodiscard attribute only applies to functions, methods, enums, and classes
auto x = [&]() [[nodiscard]] { return 1; };
// error: nodiscard attribute cannot be applied to types

这是 clang 中的某种错误还是标准中的漏洞?

c++ lambda attributes language-lawyer c++17
2个回答
20
投票

不能将

nodiscard
应用于lambda,但你可以编写一个包装器:

template <typename F>
struct NoDiscard {
    F f;
    NoDiscard(F const& f) : f(f) {}
    template <typename... T>
    [[nodiscard]] constexpr auto operator()(T&&... t) const
      noexcept(noexcept(f(std::forward<T>(t)...))) {
        return f(std::forward<T>(t)...);
    }
};

int main() {
    NoDiscard([](int i) {return i;})(0);
}

演示


0
投票

在C++23中你可以这样做:

auto lambda = [] [[nodiscard]] (/*parameters*/)
{
    // ...
};

参数列表是可选的。

[[...]]
周围的空格是可选的。

模板参数

<...>
(如果有)位于属性之前。

© www.soinside.com 2019 - 2024. All rights reserved.