从非类型模板参数推导值类型

Value type deduction from non-type template parameter

我目前正在尝试实现一个小模板,它推断出存储作为模板参数给定的特定位数所需的类型:

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

也许有人可以指点一些有用的文字或 告诉我我的方法有什么问题?

您需要 type 成员,而不是数据成员:

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;
    // ...
}