Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 737
Leonhart Squall Avatar asked Dec 16 '14 06:12

Leonhart Squall


2 Answers

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.

Try this:

constexpr const char* p = "1234567";

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);
like image 76
Potatoswatter Avatar answered Oct 27 '22 09:10

Potatoswatter


In C++17, you can use std::char_traits::length

constexpr auto l = std::char_traits<char>::length("123");//string("123").length();
cout << l;
like image 34
Zhang Avatar answered Oct 27 '22 10:10

Zhang