运行 作为 constexpr 和没有 constexpr 的函数
Run function both as constexpr and without constexpr
我有一个生成伪随机数的class。
我需要 运行 constexpr 函数中的伪随机数生成器函数(我需要它在编译时生成它)和 运行-time
它工作得很好,但我想知道是否有一些方法可以执行以下操作:
我想要一个生成数字的函数,并且我可以在编译时或 运行 时判断我是否需要它。那是因为如果我写 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.
如果你想要一个只能在运行时使用的函数,那么你只需使用一个"plain"函数:
int f() { return 42; }
如果你想要一个只能在编译时使用的函数,那么你可以使用consteval
函数:
consteval int f() { return 42; }
我有一个生成伪随机数的class。
我需要 运行 constexpr 函数中的伪随机数生成器函数(我需要它在编译时生成它)和 运行-time
它工作得很好,但我想知道是否有一些方法可以执行以下操作:
我想要一个生成数字的函数,并且我可以在编译时或 运行 时判断我是否需要它。那是因为如果我写 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.
如果你想要一个只能在运行时使用的函数,那么你只需使用一个"plain"函数:
int f() { return 42; }
如果你想要一个只能在编译时使用的函数,那么你可以使用consteval
函数:
consteval int f() { return 42; }