Search code examples
c++c++11templateslambdanoexcept

Check if a lambda is noexcept


I'm trying to check if a lambda is noexcept or not

but it looks like noexcept(lambda) doesn't do what I think it should.

auto lambda = [&](Widget& w){
    w.build();
};

auto isNoexcept = noexcept(lambda) ? "yes" : "no";
std::cout << "IsNoexcept: "  << isNoexcept << std::endl;

This prints "IsNoexcept: yes" even through the lambda is not marked noexcept.

What am I doing wrong here?

https://godbolt.org/z/EPfExoEad


Solution

  • The lambda needs to be called, e.g.

    auto isNoexcept = noexcept(lambda(std::declval<Widget&>())) ? "yes" : "no";
    

    noexcept is used to check the expression throws or not, while the expression lambda, the lambda itself won't throw, until it's invoked (with specified arguments).