ruhig brauner
ruhig brauner

Reputation: 963

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.

Upvotes: 2

Views: 254

Answers (1)

Chris Uzdavinis
Chris Uzdavinis

Reputation: 6131

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.

Upvotes: 1

Related Questions