我想防止人们在不处理返回值的情况下调用 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 中的某种错误还是标准中的漏洞?
You 无法申请nodiscard到 lambda http://eel.is/c++draft/dcl.attr.nodiscard#1,但你可以写一个包装器:
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);
}
Demo https://wandbox.org/permlink/BdT5TXem9Qo0zZau.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)