编译时constexpr错误,但运行时无开销 [英] constexpr error at compile-time, but no overhead at run-time

查看:286
本文介绍了编译时constexpr错误,但运行时无开销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There is a well-known trick to cause a compile-time error in the evaluation of a constexpr function by doing something like this:

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

如果该函数用于 constexpr 上下文,如果 x == 0 ,您将收到编译时错误。但是,如果 f 的参数不是 constexpr ,则在运行时如果 x == 0 ,出于性能原因可能并不总是希望如此。

And if the function is used in a constexpr context you will get a compile-time error if x == 0. If the argument to f is not constexpr, however, then it will throw an exception at run time if x == 0, which may not always be desired for performance reasons.

类似于 assert 受 NDEBUG 的保护,有没有一种方法导致 constexpr 函数,但在运行时什么都不做?

Similar to the theory of assert being guarded by NDEBUG, is there a way to cause a compile-time error with a constexpr function, but not do anything at run time?

最后,在C语言中使用宽松的 constexpr 规则++ 1y(C ++ 14)更改任何内容吗?

Finally, do relaxed constexpr rules in C++1y (C++14) change anything?

推荐答案

是否有导致编译时的方法? constexpr 函数出错,但在运行时什么都不做?

Is there a way to cause a compile-time error with a constexpr function, but not do anything at run time?

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

You can use the exact same trick, but instead of using a throw-expression, use an expression that is not a constant expression but does what you want at runtime. For instance:

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

放松 constexpr C ++ 1y(C ++ 14)中的规则会发生变化吗?

Do relaxed constexpr rules in C++1y (C++14) change anything?

不在此区域,否。有些形式的表达式在C ++ 14的常量表达式中有效,但在C ++ 11的常量表达式中无效,但 throw-expressions 或对non- constexpr <的调用/ code>函数在该列表上。

Not in this area, no. There are some forms of expression that are valid in constant expressions in C++14 but not in C++11, but neither throw-expressions nor calls to non-constexpr functions are on that list.

这篇关于编译时constexpr错误,但运行时无开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆