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

编程入门 行业动态 更新时间:2024-10-26 22:24:22
本文介绍了如何将[[nodiscard]]属性应用于lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I want to prevent people from calling the lambda without handling the return value.

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

Clang 4.0 refuses everything I've tried, compiling with -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

这是叮当声中的某种错误还是标准中的漏洞?

Is this some sort of bug in clang or a hole in the standard?

推荐答案

您不能将nodiscard应用于lambdas ,但是您可以编写包装器:

You can't apply nodiscard to lambdas, but you can write a wrapper:

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

演示.

更多推荐

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

本文发布于:2023-11-12 09:32:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581122.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用于   如何将   属性   lambda   nodiscard

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!