运行函数作为 constexpr 和不作为 constexpr
Run function both as constexpr and without constexpr
我有一个生成伪随机数的类。
我需要在 constexpr 函数中运行伪随机数生成器函数(我需要它在编译时生成它(和运行时
它运行良好,但我想知道是否有某种方法可以执行以下操作:
我想要一个生成数字的函数,我可以在编译或运行时告诉我是否想要它。 那是因为如果我写 2 个不同的代码,我必须重写相同的代码两次,这使得使用起来稍微不那么直观
我考虑过像这样使用定义:
#ifdef COMPILETIME
int constexpr function();
#else
int function();
#endif
但所有定义都是全局的。 我不能在我想通过代码时取消定义和重新定义它们
有没有办法实现这一点,或者我是否永远注定要使用 2 个单独的功能?
constexpr
函数可以在编译时和运行时调用。根据调用函数的上下文,将相应地对其进行计算。例如:
constexpr int f() { return 42; }
int main()
{
int a[f()]; // array bounds must be compile time, so f is called at compile time
int b = f(); // not a constant evaluation context, so called at run-time
}
请注意,如果要在编译时计算函数,但将其存储到要在运行时更改的变量中,则可以执行以下操作:
int const x = f(); // compile time calculation
int a = x; // work done, but value of a can be changed at run-time.
如果你想要一个只能在运行时使用的函数,那么你只需要使用一个"普通"函数:
int f() { return 42; }
如果你想要一个只能在编译时使用的函数,那么你可以使用consteval
函数:
consteval int f() { return 42; }
相关文章:
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 运行函数作为 constexpr 和不作为 constexpr
- 代码作为 C 文件工作,但不作为C++文件,错误:'__builtin_types_compatible_p'未在此范围内声明
- 从语言设计层面来看,当编译时无法推断条件时,为什么"if constexpr"不衰减到"trival if"
- Constexpr 函数作为 SFINAE 的模板参数
- 检查不作为单个条目的STDIN输入
- 为什么可变参数函数模板中的这个 constexpr 不是常数?
- 为什么 if constexpr 不会使这个核心常量表达式错误消失?
- Enable_if如果使用constexpr函数作为参数,则不在Visual Studio中工作
- 为什么"if constexpr"不使用Visual Studio 2017 15.3进行编译?
- 在C 中,为什么使用或不作为结果值获得不同的结果
- 为什么在 C++11 中不能使用 constexpr 指针作为模板参数?
- 声明并初始化指针后,何时在变量文本前面加上星号,何时不作为前缀
- 在不作为超级用户的情况下更改文件权限
- C++:为什么这个 constexpr 不是编译时常数
- constexpr char[] 作为类成员有什么好处
- 为什么constexpr不是自动的
- 为什么字符串文本不作为对数组的引用而不是不透明指针传递?
- 将全局constexpr类作为静态constexpr移动到类中
- 不作为const的临时