8

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?

Giovanni Cerretani
  • 1,693
  • 1
  • 16
  • 30

2 Answers2

3

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'");
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
0

You could use SFINAE to solve this problem. Consider the following code:

template <class T>
class has_a
{
    template <class C>
    static std::true_type test(C, C = C::a);

    template <class C>
    static std::false_type test(...);

public:
    using type = T;
    static bool constexpr value = decltype(test<T>(T{}))::value;
};

Then, you can just:

static_assert(has_a<e>::value, "Given type is incorrect.");
Tihran
  • 106
  • 4