Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to statically assert if enumeration constant is defined?

I've this C++14 code:

#include <type_traits>

struct f1 {
    enum struct e { a };
};

struct f2 {
    enum struct e {};
};

template <typename T>
struct my_struct {
    using e = typename T::e;
    my_struct()
    : _e{e::a} {} // e::a used here
    e _e;
};

int main() {
    my_struct<f1> a;
    my_struct<f2> b; // compilation fails
}

Obviously the compilation fails with something like 'a' is not a member of 'my_struct<f2>::e'. I really would like to add some static assertions to my_struct, to add a custom error message. First of all, I can check if e is actually an enumeration:

static_assert(std::is_enum<e>::value, "my message");

Then, what should I add to statically assert that e::a is defined?

like image 959
Giovanni Cerretani Avatar asked Jun 15 '20 10:06

Giovanni Cerretani


Video Answer


1 Answers

The same way as you would detect any nested declaration:

template <typename T, typename = void>
struct enum_defines_a : std::false_type {};

template <typename T>
struct enum_defines_a<T, decltype(void(T::a))> : std::is_enum<T> {};

static_assert(enum_defines_a<e>::value, "Enum doesn't define 'a'");
like image 51
Piotr Skotnicki Avatar answered Nov 13 '22 15:11

Piotr Skotnicki