I'm trying to play around with constexpr and static_assert. I actually need to check the length of a constexpr string, which is calculated by a dedicated function. Here is what I'm trying to run:
#include <iostream>
class Test
{
private :
static constexpr char str[] = "abc";
static int constexpr constStrLength(const char* str)
{
return *str ? 1 + constStrLength(str + 1) : 0;
}
static constexpr int length = constStrLength(str); // error here
static_assert(length == 3, "error");
public :
static void f()
{
std::cout << length << std::endl;
}
};
int main()
{
Test::f();
}
And here is the error I get:
error: 'static constexpr int Test::constStrLength(const char*)' called in a constant expression static constexpr int len = constStrLength("length ");
What's the right way to achieve it?
char str[] = "..."? Because you could get the length simply assizeof(str)-1in this form.sizeof("abc\0def") - 1yields7while theconstStrLength()function would yield3.