gpt4 book ai didi

c++ - constexpr 重载

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:49:56 24 4
gpt4 key购买 nike

相关:Function returning constexpr does not compile

我觉得 constexpr 在 C++11 中的用途有限,因为无法定义两个函数,否则这两个函数将具有相同的签名,但一个是 constexpr,另一个不是 constexpr。换句话说,如果我可以拥有一个仅接受 constexpr 参数的 constexpr std::string 构造函数,以及一个用于非 constexpr 参数的非 constexpr std::string 构造函数,那将非常有帮助。另一个例子是一个理论上复杂的函数,可以通过使用状态来提高效率。你不能用 constexpr 函数轻易做到这一点,所以你有两个选择:有一个 constexpr 函数,如果你传入非 constexpr 参数,它会非常慢,或者完全放弃 constexpr (或者写两个单独的函数,但您可能不知道调用哪个版本)。

因此,我的问题是:

符合标准的 C++11 实现是否有可能允许基于参数为 constexpr 的函数重载,或者这是否需要更新标准?如果不允许,是故意不允许的吗?


@NicolBolas:假设我有一个将 enum 映射到 std::string 的函数。假设我的 enum0n - 1,最直接的方法是创建一个大小为 n 填充结果。

我可以创建一个 static constexpr char const * [] 并在返回时构造一个 std::string(支付创建 std::的成本) string object per time I call the function),或者我可以创建一个 static std::string const [] 并返回我查找的值,支付所有 std::string 构造函数,我第一次调用该函数。似乎更好的解决方案是在编译时在内存中创建 std::string(类似于现在使用 char const * 所做的),但唯一的这样做的方法是提醒构造函数它有 constexpr 参数。

对于 std::string 构造函数以外的示例,我认为找到一个示例非常简单,如果您可以忽略 constexpr (从而创建一个非 constexpr 函数),您可以创建一个更高效的函数。考虑这个线程:constexpr question, why do these two different programs run in such a different amount of time with g++?

如果我用 constexpr 参数调用 fib,我无法比编译器完全优化函数调用做得更好。但是如果我用非 constexpr 参数调用 fib ,我可能想让它调用我自己的版本来实现诸如内存(这需要状态)之类的东西,所以我得到如果我传递了一个 constexpr 参数,运行时间类似于我的编译时间。

最佳答案

我同意缺少此功能 - 我也需要它。示例:

double pow(double x, int n) {
// calculate x to the power of n
return ...
}

static inline double pow (double x, constexpr int n) {
// a faster implementation is possible when n is a compile time constant
return ...
}

double myfunction (double a, int b) {
double x, y;
x = pow(a, b); // call version 1 unless b becomes a compile time constant by inlining
y = pow(a, 5), // call version 2
return x + y;
}

现在我必须使用模板来做到这一点:

template <int n>
static inline double pow (double x) {
// fast implementation of x ^ n, with n a compile time constant
return ...
}

这很好,但我错过了重载机会。如果我制作一个库函数供其他人使用,那么用户必须根据 n 是否为编译时常量来使用不同的函数调用是不方便的,并且可能很难预测编译器是否已将 n 减少为 a是否编译时间常数。

关于c++ - constexpr 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55196161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com