本文介绍了如何将[[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 typesauto 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?
发布评论