Romà Pagès
Romà Pagès

Reputation: 11

check a c string at compile time in c++

I want to validate a c string at compile time (using static assert). I have already a constexpr function that is able to do. (I use C++17)

template <std::size_t N>
constexpr bool validate(const char (&name)[N]) {
   /* ... */
   return false;
}

Now I would like to add another constexpr function like this:

template <std::size_t N>
constexpr const char* VALIDATE(const char (&name)[N]) {
    static_assert(validate(name), "wrong name");
    return &name[0];
}

because I want to use it as follows:

class GenericClass {
public:
    virtual const char* getName() const = 0;
};

class MyClass final: public GenericClass {
public:
    const char* getName() const override {
        return VALIDATE("MyClass");
    }
};

I want to make sure at compile time that all classes derived from GenericClass have an appropriate name.

When I test this code I get the following compilation error:

"error: non-constant condition for static assertion" at static_assert(validate(name), "wrong name"); line

I have tried several things but I can't figure out how to call the validate function inside the VALIDATE function without losing the constexpr condition of the name given when VALIDATE is called with a constexpr C string.

Thanks

Upvotes: 1

Views: 29

Answers (0)

Related Questions