c++ - 编译时 constexpr 错误,但运行时没有开销

标签 c++ c++11 constexpr c++14

有一个众所周知的技巧可以通过执行以下操作在 constexpr 函数的评估中导致编译时错误:

constexpr int f(int x) {
    return (x != 0) ? x : throw std::logic_error("Oh no!");
}

如果在 constexpr 上下文中使用该函数,如果 x == 0 则会出现编译时错误。但是,如果 f 的参数不是 constexpr,那么如果 x == 0,它将在运行时抛出异常,这可能不会出于性能原因总是需要的。

类似于 assertNDEBUG 保护的理论,有没有办法用 constexpr 函数导致编译时错误,但在运行时不执行任何操作?

最后,C++1y (C++14) 中宽松的 constexpr 规则有什么改变吗?

最佳答案

有没有办法使用 constexpr 函数导致编译时错误,但在运行时不执行任何操作?

您可以使用完全相同的技巧,但不要使用 throw-expression,而是使用不是常量表达式但在运行时执行您想要的操作的表达式。例如:

int runtime_fallback(int x) { return x; } // note, not constexpr
constexpr int f(int x) {
  return (x != 0) ? x : runtime_fallback(0);
}

constexpr int k1 = f(1); // ok
constexpr int k2 = f(0); // error, can't call 'runtime_fallback' in constant expression
int k3 = f(0);           // ok

C++1y (C++14) 中宽松的 constexpr 规则会改变什么吗?

不在这个区域,不。有一些表达式形式在 C++14 中的常量表达式中有效,但在 C++11 中无效,但既不是 throw-expressions 也不是对非 constexpr 的调用函数在该列表中。

关于c++ - 编译时 constexpr 错误,但运行时没有开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20461121/

相关文章:

multithreading - 为什么不在 fill_n 中调用移动构造函数

c++ - Windows 中的可变参数列表 va_list

c++ - 如何从变量创建一个包含多个元素的数组?

c++ - 将 weak_ptr 与 unique_ptr 配对是个好主意吗?

c++ - 在 firemonkey 中加载一个 dylib

c++ - 如何将模板可变参数存储到 std::ofstream 中?

c++ - 如果超时已过,如何中止 async()

c++ - 静态 constexpr 方法实现导致 gcc 错误?

c++ - 声明 constexpr 函数或方法

c++ - 我们可以在 constexpr 函数中省略局部变量的 const 吗?