Search code examples
c++templatestypesargumentsdefault

Template argument with default type and value


I would like to give a template argument a default type and value. The argument isn't really used, it's only relevant to distinguish class instances. I want to use the mechanic for to give classes a key.

I'm trying something like this but the compiler doesn't like it

template<typename K = int>
template<typename T, K Key = K(0)>
class DataAction : public Action
{
    // ...
};

Type T hold data for me. Type Key is of some value to allow for easy use of enum class types and should default to int 0 if not assigned.

The following would work.

template<typename T, typename K = int, K Key = K(0)>
class DataAction : public Action

But it requires me to first define the type and then the value, which is not nice.

auto instance = DatatAction<int, SomeEnumType, SomeEnumType::SomeKey>();

The intention is that the user might want to use multiple class instances of DataAction with the same data type T. To be able to distinguish between them in a dynamic_cast, which is required anyway, an additional key type is used.


Solution

  • In C++17 you can use an auto template parameter:

    template <typename T, auto = 0>
    class DataAction : public Action
    {
    }
    

    Here 0 is an int, but you could assign (char)0 or other types too, if you really want to be confusing with different types of the same value. :)

    Personally I prefer a single type and no defaults for this kind of thing. This avoids most accidental key reuse and confusion by onlookers.