C ++ 11 get string length at constexpr compilation

#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;
}

Hi, everyone. I want to get the length of the string in compile-time. So I wrote the code above. But in the disassembly code, I found that the constLength function, called sub_401000 below, will lead to runtime overhead to calculate the length of the string. Is there something wrong there? (Preview of Visual Studio 2015 Release at Maximum Speed ​​Optimization (/ O2))

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;
}
+4
source share
2 answers

A constexpr , . p ( ), .

:

constexpr const char* p = "1234567";

, , , constexpr:

constexpr size_t i = constLength(p);
+7

, . -, . "" .

. static_eval.h. :

template<typename T, T V>
struct static_eval
{
    static constexpr T value = V;
};

, :   //size_t i = constLength (p);   size_t i = static_eval :: value;

, constexpr.

0

All Articles