c ++ 11通过constexpr在编译时获取字符串长度 [英] c++11 get string length in compile time by constexpr
问题描述
#include <stdio.h>
constexpr size_t constLength(const char* str)
{
return (*str == 0) ? 0 : constLength(str + 1) + 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
const char* p = "1234567";
size_t i = constLength(p);
printf(p);
printf("%d", i);
return 0;
}
您好,所有
我都想获取字符串的长度因此,我在上面编写了代码。但是在反汇编代码中,我发现下面的名为sub_401000的'constLength'函数将导致计算字符串长度的运行时开销。是否有问题?(Visual Studio 2015 Preview,释放并以最大化速度(/ O2)优化)
Hi,all I want to get the length of a string in compile-time.So i wrote the code above.But in disassembly code i found 'constLength' function that named sub_401000 below will lead run-time overhead for computting the length of string.Is there something wrong?(Visual Studio 2015 Preview,release with Maximize Speed (/O2) optimization)
int __cdecl sub_401010()
{
int v0; // esi@1
v0 = sub_401000("234567") + 1;
sub_401040(&unk_402130);
sub_401040("%d");
return 0;
}
int __thiscall sub_401000(void *this)
{
int result; // eax@2
if ( *(_BYTE *)this )
result = sub_401000((char *)this + 1) + 1;
else
result = 0;
return result;
}
推荐答案
A constexpr
函数只能在使用编译时常量的参数调用时在编译时求值。尽管 p
的值可以通过静态分析确定(在初始化和评估之间不会改变),但根据标准定义,它不是常数表达式。
A constexpr
function can only be evaluated at compile time when called with arguments that are compile-time constants. Although the value of p
can be determined by static analysis (it doesn't change between initialization and evaluation), it's not a constant expression per the standard definition.
尝试一下:
constexpr const char* p = "1234567";
另外,您可以通过将初始化变量声明为<$来保证初始化是可行的,而不会增加运行时的开销c $ c> constexpr :
Also, you can guarantee that an initialization is doable without runtime overhead by declaring the initialized variable as constexpr
:
constexpr size_t i = constLength(p);
这篇关于c ++ 11通过constexpr在编译时获取字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!