3

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;
5
  • Perhaps this answers your question? It uses a function parameter instead of a local/global variable. Commented Dec 26, 2020 at 16:56
  • 6
    if variable is constexpr, yes. Commented Dec 26, 2020 at 16:57
  • 1
    Could you clarify your example code? Currently it's not clear what you want, and your use of C makes no sense Commented Dec 26, 2020 at 16:58
  • Any reason you don't use C<E1>? Commented Dec 26, 2020 at 17:58
  • Depending on a string, I need to return an enum type. I want to use that type directly in another method. Commented Dec 26, 2020 at 23:18

1 Answer 1

3

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 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.