【发布时间】:2017-04-28 18:05:25
【问题描述】:
我想防止人们在不处理返回值的情况下调用 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 中的某种错误还是标准中的漏洞?
【问题讨论】:
-
[expr.prim.lambda] 建议
[&]() [[nodiscard]] { return 1; }。 -
...但是,[dcl.attr.nodiscard] 不允许在 lambda 中使用该特定属性。如果我不得不猜测,我会说这是因为它几乎没有用处:lambdas 通常作为回调传递给代码的其他部分,因此无论如何都无法检查 nodiscardiness。
-
嗯,您编辑的问题似乎已经包含您在诊断过程中需要的确切答案:-S
-
我经常将它们用作本地函数,在这种情况下,nodiscardiness 是相关的,除非我完全误解了 nodiscardiness。
-
当然,但如果仅在本地使用,您可以查看是否调用它们。将 API 函数标记为 nodiscard 的价值在于,
vector::empty之类的东西不会被第三方误解。如果是你自己的代码,那问题就小得多了。
标签: c++ lambda attributes language-lawyer c++17