Подтвердить что ты не робот

Как я могу применить атрибут [[nodiscard]] к лямбда?

Я хочу, чтобы люди не вызывали лямбда без обработки возвращаемого значения.

Clang 4.0 отказывается от всего, что я пробовал, компилируя с -std = С++ 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 или дыре в стандарте?

4b9b3361

Ответ 1

Вы не можете применить nodiscard к 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);
}

Демо.