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);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With