gpt4 book ai didi

c++ - constexpr 重载

转载 作者:IT老高 更新时间:2023-10-28 14:00:26 26 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 对象每次调用函数),或者我可以创建一个 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 ,我可能希望它调用我自己的版本来实现诸如 memoization 之类的东西(这将需要状态)所以我得到运行时间类似于我传递 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 减少到编译时间常数与否。

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

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