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

Dan*_*son 14 c++ lambda attributes language-lawyer c++17

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

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

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

这是铿锵声中的某种错误还是标准中的漏洞?

Col*_*mbo 12

不能申请nodiscardlambdas,但你可以写一个包装器:

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);
}
Run Code Online (Sandbox Code Playgroud)

演示.

  • 对于像我这样挑剔的人来说,将 const noexcept(noexcept(f(std::forward&lt;T&gt;(t)...))) 添加到“operator()”怎么样?:) (2认同)