我目前正在尝试实施一个小模板,该模板推导出存储作为模板参数给定的一定数量的位所需的类型:
template<unsigned char BITS>
class Register
{
public:
unsigned long type;
};
此外,我尝试将此模板专门用于某些位尺寸:
template<>
class Register<8>
{
public:
unsigned char type;
};
template<>
class Register<16>
{
public:
unsigned short type;
};
template<unsigned int N> Register<N+1>;
不幸的是,这并没有按预期工作,也无法编译:
int _tmain(int argc, _TCHAR* argv[])
{
Register<32>::type val32 = 0xDEADBEEF;
assert(sizeof(val) == sizeof(unsigned long) );
Register<16>::valType val16 = 0xBEEF;
assert(sizeof(val) == sizeof(unsigned short) );
Register<8>::valType val8 = 0xEF;
assert(sizeof(val) == sizeof(unsigned char) );
Register<4>::valType val4 = 0xF;
assert(sizeof(val) == sizeof(unsigned char) );
return 0;
}
也许有人可以给我指向一些有用的文字或 告诉我我的方法有什么问题?
答案 0 :(得分:5)
您需要类型成员,而不是数据成员:
template <std::size_t N> struct Register
{
using type = unsigned long int;
};
template <> struct Register<8>
{
using type = unsigned char;
};
// ...
用法:
template <typename T> void f()
{
typename Register<sizeof(T) * CHAR_BIT>::type thing;
// ...
}