模板 class 接受类型名或不带自动的 int

template class which accepts either a typename or int without auto

是否可以根据给定的内容让 class 模板接受一个 (unsigned inttypename) 参数?

我的意思的例子:

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

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

Bytes<DWORD64> EightBytes;

我知道 template<auto T>,但在想是否有不同的解决方案?

模板参数必须是类型或值,对于可以是类型或值的内容没有占位符。也就是说,您可以制作几个工厂功能来帮助您。这可能看起来像

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>{}; }

你会像这样声明对象

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

auto EightBytes = make_bytes<DWORD64>();