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

How can I apply the [[nodiscard]] attribute to a lambda?

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