Stukata
Stukata

Reputation: 35

How can I use a enum variable as template argument?

If we have an enumeration type:

enum E {
   E1,
   E2,
   // ...
};

and based on E, a class template:

template <E T>
class C { /* ... */ };

Is there a way of using a declared variable of the type E as a template argument?

Example code:

E example_type = E1;
C<example_type> example_class;

Upvotes: 3

Views: 142

Answers (1)

alex_noname
alex_noname

Reputation: 32143

For integral (which an enumeration is) and arithmetic types, the template argument provided during instantiation must be a constant expression. For example:

enum E {
   E1,
   E2,
};


template <E enum_val>
class Foo {
};

int main() {

    constexpr E var = E1;
    const E var2 = E2;
    Foo<var> foo;
    Foo<var2> foo2;

    E var3 = E2;
    Foo<var3> foo3;  // error: the value of ‘var3’ is not usable in a constant expression 
}

Upvotes: 3

Related Questions