【发布时间】:2012-02-14 17:33:28
【问题描述】:
相关: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 的函数。假设我的enum 从0 变为n - 1,最直接的方法是创建一个大小为n 的数组,其中填充了结果。
我可以创建一个static constexpr char const * [] 并在返回时构造一个std::string(支付每次调用函数时创建std::string 对象的成本),或者我可以创建一个static std::string const [] 并返回值 I查找,在我第一次调用该函数时支付所有 std::string 构造函数的成本。似乎更好的解决方案是在编译时在内存中创建std::string(类似于现在使用char const * 所做的),但这样做的唯一方法是提醒构造函数它具有@987654338 @参数。
对于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 参数的时间。
【问题讨论】:
-
你确定你真的需要这个吗?使用非常量参数调用
constexpr函数是完全可以的。 -
引用this paper seems relevant to your question。
We don’t propose to make constexpr applicable to function arguments because it would be meaningless for non-inline functions (the argument would be a constant, but the function wouldn’t know which) and because it would lead to complications of the overloading rules (can I overload on constexpr-ness? — no). -
我更新了我的问题以回复 Nicol Bolas。它还应该回答 Kerrek SB 提出的问题。
-
我也想要这个。另一个有用的例子是位字段的位/总体计数。许多处理器为此包含特殊指令,因此如果使用非 constexpr 参数调用 constexpr 函数,我想使用处理器指令。但是处理器指令在编译时不可用,所以我需要在编译时使用另一个算法。
-
@Adam:不。我正在写一篇针对 C++23 的论文:github.com/davidstone/isocpp/blob/master/…
标签: c++ c++11 overloading compile-time-constant constexpr