c++11 - is_defined constexpr 函数

标签 c++11 c++14 constexpr

我需要知道在指定 noexcept 说明符时是否定义了 NDEBUG。我在考虑这个 constexpr 函数:

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

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

然后像这样使用它:

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

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

最佳答案

只用#ifdef?

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

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

或无数其他类似的方式:constexpr 函数返回 boolstd::true_type(有条件地)。两种类型之一的 static 变量。一个特征类,它采用一个枚举,其中列出了各种 #define token 等价物(eNDEBUG 等),这些 token 可以专门用于它支持的每个此类 token ,​​并在以下情况下生成错误没有这样的支持。使用 typedef 而不是 using(如果你的编译器对 using 的支持不稳定,我正在看你的 MSVC2013)。我敢肯定还有其他人。

关于c++11 - is_defined constexpr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29142256/

相关文章:

c++ - 如何以静态方式使用另一个 constexpr 数组初始化一个数组

c++ - 为什么在使用 const_iterators 时可以将元素插入 vector 中

C++11 访问具有限定名称的无作用域枚举数

c++ - 函数 typedefs 中的 noexcept 说明符

c++ - 在映射最小值和最大值时从无符号转换为有符号的最佳方法?

c++ - 交换包含不可平凡复制类型的 `std::aligned_storage` 实例 - 未定义的行为?

linux - 在 Amazon Linux 上安装 g++ 5

C++11 constexpr 函数编译器错误与三元条件运算符 (? :)

c++ - 调用模板参数 constexpr 方法?

c++ - 将常规函数绑定(bind)到 std::function