Lupor
Lupor

Reputation: 59

template class which accepts either a typename or int without auto

Is it possible to have a class template accept either of one (unsigned int, typename) parameter, based upon what was given?

Example of what I mean:

template<??>
class Bytes
{
   // ....
};

Bytes<4> FourBytes;
Bytes<int> FourBytes;

Bytes<DWORD64> EightBytes;

Iam aware of the template<auto T>, though was thinking if there was a different solution?

Upvotes: 3

Views: 199

Answers (1)

NathanOliver
NathanOliver

Reputation: 180935

Template parameters need to either be a type, or a value, there isn't a placeholder for something that can be either a type or a value. That said, you can make a couple factory functions to help you. That could look like

template<std::size_t N>
class Bytes
{
   // ....
};

template <typename T>
auto make_bytes() { return Bytes<sizeof(T)>{}; }

template <std::size_t N>
auto make_bytes() { return Bytes<N>{}; }

and you would declare objects like

auto FourBytesValue = make_bytes<4>();
auto FourBytesType = make_bytes<int>();

auto EightBytes = make_bytes<DWORD64>();

Upvotes: 10

Related Questions