简体   繁体   中英

How to define an enum type which includes a templated parameter ( C++ )

I would like to define a type T as an enum which can take values {A, B, C, S1, ..., Sk} but since k is a compile-time variable I can't just type that.

template <size_t k>
struct T {
   enum class {
      A, B, C, S_1, ..., S_k
   };
};

How can I define the type?

This is not with an enum but it gives a very similar syntax (requires C++14 or higher):

template<size_t k>
struct T {
    struct MyEnum {
        static constexpr int A = 0;
        static constexpr int B = 1;
        static constexpr int C = 2;
        template<size_t n,
            typename = typename std::enable_if<n != 0 && n <= k>::type>
        static constexpr int S = Enum::C + n;
    };
};

And to access:

 int test1 = T<2>::MyEnum::A;
 int test2 = T<2>::MyEnum::S<2>; // Equivalent to S_2
 int test3 = T<2>::MyEnum::S<3>; // Compile error: 3 > 2
 int test4 = T<2>::MyEnum::S<0>; // Compile error: 0 < 1

The syntax is similar except for the angle brackets and will all be computed at compile so no run time overhead.

If you want these to return an enum you can always define your own and swap int for your enum (the downside being you can't name the struct and the enum the same name ofcourse).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM