Check length of string literal at compile time

This is C++, where there are superior options to macros. A template can give you the exact semantics your want.

template<std::size_t N>
constexpr auto& STR(char const (&s)[N]) {
    static_assert(N < 10, "String exceeds 10 bytes!");
    // < 11 if you meant 10 characters. There is a trailing `\0`
    // in every literal, even if we don't explicitly specify it
    return s;
}

The array reference argument will bind to string literals, not pointers (that can trip your macro), deduce their size, and perform the check in the body of the function. Then it will return the reference unchanged if everything checks out, allowing even for continued overload resolution.


I will add to @StoryTeller - Unslander Monica great answer, If you need (like me) to pass and argument for string's max length, you can expand the implementation to be more generic :

template<const int MAX_LEN, std::size_t N>
constexpr auto& STR(char const (&s)[N]) 
{
    static_assert(N < MAX_LEN, "String overflow!");
    return s;
}

And if you need several known length's, you can use template specialization :

template<std::size_t N>
constexpr auto & STR16(char const (&s)[N])
{
    return STR<16>(s);
}

The first function can be a generic version, where's the second can have access to project's consts.

Tags:

C++