C ++ constexpr在编译时 [英] C++ constexpr at compile time
问题描述
我是否有理由认为此函数应该只在编译时进行评估,或者是否有运行时成本?
Am I right to think that this function should only be evaluated at compile time, or is there a run-time cost to it?
template <typename T>
size_t constexpr CompID() {
return typeid(T).hash_code();
}
struct Foo {};
int main(int argc, const char * argv[]) {
size_t foo = CompID<Foo>();
return 0;
}
推荐答案
constexpr函数允许函数在编译时被评估,但不要求,所以你的答案是也许。这取决于编译器的优化设置。
constexpr function allows the function to be evaluated at compile time, but does not require that, so your answer is "maybe". It depends on the compiler's optimization settings.
§7.1.5[dcl.constexpr] / 7
对
constexpr
函数的调用产生的结果与调用相同的非constexpr
function
在所有方面,除了调用constexpr
函数可以出现在常量表达式中。
§7.1.5[dcl.constexpr]/7
A call to a
constexpr
function produces the same result as a call to an equivalent non-constexpr
function in all respects except that a call to aconstexpr
function can appear in a constant expression.
如果你不希望没有运行时成本,你可以通过将它分配给一个constexpr变量来强制编译时评估,例如
If you wish to have no runtime cost, you could force compile-time evaluation by assigning it to a constexpr variable, e.g.
constexpr auto foo = CompID<Foo>();
另请注意 type_info.hash_code()
无法在编译时评估(它不是constexpr函数,§18.7.1[type.info] / 7)。所以你的代码其实是错误的。
Also note that type_info.hash_code()
cannot be evaluated in compile-time (it is not a constexpr function, §18.7.1[type.info]/7). So your code is actually wrong.
这篇关于C ++ constexpr在编译时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!