Passer By
Passer By

Reputation: 21160

Using a constexpr C-string as compiler error message

As the question suggests what I would like to do is

template<const char* Err>
struct broken
{
    template<typename... Args>
    constexpr broken(Args&&...)
    {
        //the sizeof... confuses the compiler as to only emit errors when instantiated
        //this does not work, static_assert only accepts string literals
        static_assert(sizeof...(Args) < 0, Err);
    }
};

What I hope for is that broken emit an compiler error message Err whenever instantiated. However, static_assert exclusively accepts only a string literal as its second argument. Is there any way to emit a compiler error based on a constexpr string?

Upvotes: 4

Views: 145

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 120031

What you want cannot possibly work in any shape or form, because you can legitimately do

extern const char foo[];
template <const char* err> class broken {};
broken<foo> tisbroken;

and foo need not even be defined in the current TU (or anywhere else for that matter) for this to compile.

An ODR-use of err inside foo would lead to a linker error when foo is undefined, but that would be way too late.

So no, you cannot use a string passed to a template to print compiler messages, because there's no string.

Upvotes: 1

Related Questions