blog, c++,

strlen at compile time

Jing Chi Jing Chi Follow Aug 06, 2019 · 1 min read
strlen at compile time
Share this

You have a class with a name, and you need to calculate its size and allocate memory for it, how to do this?

class A
{
public:
    static constexpr const char* const name = "Class A";
};

constexpr std::size_t __strlen(const char* const str)
{
    return str[0] == '\0' ? 0 : 1 + __strlen(str + 1);
}

template <typename T>
constexpr std::size_t __sizeof_name(void) noexcept
{
    return __strlen(T::name) + 1;
}