3

I need to know whether NDEBUG is defined when specifying the noexcept specifier. I was thinking along the lines of this constexpr function:

constexpr inline bool is_defined() noexcept
{
  return false;
}

constexpr inline bool is_defined(int) noexcept
{
  return true;
}

Then use it like:

void f() noexcept(is_defined(NDEBUG))
{
  // blah, blah
}

Does the standard library or the language already provide a facility for this so that I won't be reinventing the wheel?

user1095108
  • 14,119
  • 9
  • 58
  • 116

2 Answers2

5

Just use #ifdef?

#ifdef  NDEBUG
using is_ndebug = std::true_type;
#else
using is_ndebug = std::false_type;
#endif

void f() noexcept(is_ndebug{}) {
  // blah, blah
}

or a myriad of other similar ways: A constexpr function returning bool or std::true_type (conditionally). A static variable of one of two types. A traits class that takes an enum which lists various #define token-equivalents (eNDEBUG etc) which can be specialized for each such token it has support for, and generates errors if there is no such support. Using typedef instead of using (if your compiler has flaky support for using, I'm looking at you MSVC2013). I'm sure there can be others.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • There are a myriad of ways, but not all of them work, because of compiler bugs. It's gcc: error `noexcept ()' has a different exception specifier` – user1095108 Mar 19 '15 at 13:58
2

If you are only interested in NDEBUG, this is equivalent to testing whether assert() evaluates it's argument or not. In that case, you can use:

void f() noexcept(noexcept(assert((throw true,true))))
{
    // ...
}

This is, of course, not necessarily an improvement :)

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180