2

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

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
randomThought
  • 6,203
  • 15
  • 56
  • 72

1 Answers1

6

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).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • but noexcept(lambda()) doesn't compile since lambda takes a specific parameter. Can I check if the lambda is noexcept without passing in an actual value? Since I want the template function to be noexcept or not – randomThought May 15 '21 at 06:22
  • @randomThought Not in general, because you can make a functor with an overloaded `operator()`, with only some of the overloads `noexcept`. If you're certain it's not overloaded and not templated, you could form a pointer-to-member to it, then use template specialization to see if it has noexcept in it. – HolyBlackCat May 15 '21 at 06:24
  • 2
    @randomThought Arguments are required to call the lambda, you can construct them in-place like `lambda(std::declval())`. – songyuanyao May 15 '21 at 06:26
  • lambda(std::declval()) was the missing piece. Thanks – randomThought May 15 '21 at 06:28