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

时间:2017-04-28 18:05:25

标签: c++ lambda attributes language-lawyer c++17

我想阻止人们在不处理返回值的情况下调用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

这是铿锵声中的某种错误还是标准中的漏洞?

1 个答案:

答案 0 :(得分:11)

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