Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strlen in constexpr?

Tags:

c++

clang

c++20

I'm using clang++ 13.0.1
The code below works but it's obviously ugly. How do I write a strlen? -Edit- Inspired by the answer, it seems like I can just implement strlen myself

#include <cstdio>
constexpr int test(const char*sz) {
    if (sz[0] == 0)
        return 0;
    if (sz[1] == 0)
        return 1;
    if (sz[2] == 0)
        return 2;
    return -1;
    //return strlen(sz);
}
constinit int c = test("Hi");

int main() {
    printf("C %d\n", c);
}
like image 628
Eric Stotch Avatar asked Oct 26 '25 18:10

Eric Stotch


1 Answers

You can just use C++17 string_view and get the length of the raw string through the member function size()

#include <string_view>
constexpr int test(std::string_view sz) {
  return sz.size();
}

Demo

Another way is to use std::char_traits::length which is constexpr in C++17

#include <string>
constexpr int test(const char* sz) {
  return std::char_traits<char>::length(sz);
}
like image 134
康桓瑋 Avatar answered Oct 28 '25 08:10

康桓瑋