gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:39:21 36 4
gpt4 key购买 nike

我想防止人们在不处理返回值的情况下调用 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 中的某种错误还是标准中的漏洞?

最佳答案

can't apply nodiscard to lambdas ,但你可以写一个包装器:

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 .

关于c++ - 如何将 [[nodiscard]] 属性应用于 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686374/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com