Search code examples
c++templatestemplate-variables

Deducing type of template value parameter


I was wondering if the type of a value template parameter could be deduced or obmitted when writing something similar to this:

enum class MyEnum {A, B}

enum class MyOtherEnum {X, Y}

template <typename T, T value>
struct GenericStruct {};

When using MyGenericStruct both T and value have to be passed, but T would be deducible from context typename T = decltype(value) except that value is not yet defined. template <auto value> isn't working either.

Is there any way to simply write MyGenericStruct<MyEnum::A> instead of MyGenericStruct<MyEnum, MyEnum::A> without usage of macros?


Solution

  • If you can use C++17, you can use auto as the type of the non-type template parameter. That gives you

    template <auto value>
    struct GenericStruct {};
    

    Now, value will have its type deduced by its initializer just like if you had declared a variable with type auto and gives you the desired syntax of GenericStruct<MyEnum::A> foo; as seen in this live example.