2

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.

1

1 Answer 1

1

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.

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.