让模板通过指定bitsize在char/short/int之间进行选择?

Mar*_*kus 8 c++ templates

我有这样的事情:

template<int SIZE>
struct bin {
private:
public:
    struct {
        int _value : SIZE;
    };
}
Run Code Online (Sandbox Code Playgroud)

是否可以根据SIZE更改_value的数据类型?如果SIZE <= 7,我希望_value成为char.如果它> = 8且<= 15,我希望它是短的,如果它是<= 31,我希望它是一个整数.

Ste*_*sop 10

这不是特别优雅,但是:

template <unsigned int N>
struct best_integer_type {
    typedef best_integer_type<N-1>::type type;
};

template <>
struct best_integer_type<0> {
    typedef char type;
};

template <>
struct best_integer_type<8> {
    typedef short type;
};

template <>
struct best_integer_type<16> {
    typedef int type;
};

template <>
struct best_integer_type<32> {
    // leave out "type" entirely, to provoke errors
};
Run Code Online (Sandbox Code Playgroud)

然后在你的班上:

typename best_integer_type<SIZE>::type _value;
Run Code Online (Sandbox Code Playgroud)

它没有处理负数SIZE.您的原始代码也没有,但您的文字说明是否使用charif SIZE <= 7.我希望0 <= SIZE <= 7能做到.


Geo*_*che 8

Boost.Integer具有用于类型选择的实用程序:

boost::int_t<N>::least
最小的内置有符号整数类型,至少有N位,包括符号位.参数应为正数.如果参数大于最大整数类型中的位数,则会产生编译时错误.

boost::int_t<N>::fast
最容易操作的内置有符号整数类型,至少有N位,包括符号位.参数应为正数.如果参数大于最大整数类型中的位数,则会产生编译时错误.