is_defined constexpr函数

use*_*108 3 constexpr c++11 c++14

我需要知道在指定noexcept说明符时是否定义了NDEBUG.我正在考虑这个constexpr功能:

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

constexpr inline bool is_defined(int) noexcept
{
  return true;
}
Run Code Online (Sandbox Code Playgroud)

然后使用它像:

void f() noexcept(is_defined(NDEBUG))
{
  // blah, blah
}
Run Code Online (Sandbox Code Playgroud)

标准库或语言是否已经为此提供了便利,以便我不会重新发明轮子?

Yak*_*ont 5

刚用#ifdef

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

void f() noexcept(is_ndebug{}) {
  // blah, blah
}
Run Code Online (Sandbox Code Playgroud)

或者无数其他类似的方式:constexpr函数返回boolstd::true_type(有条件地).甲static两种类型之一的变量.一个traits类,它带有一个枚举,列出了各种#define令牌等价物(eNDEBUG等等),它们可以专门用于它支持的每个这样的令牌,如果没有这样的支持就会产生错误.使用typedef而不是using(如果你的编译器支持使用,我正在看你MSVC2013).我相信可能还有其他人.