我有这样的东西:
template<int SIZE>
struct bin {
private:
public:
struct {
int _value : SIZE;
};
}
是否可以根据 SIZE 更改 _value 的数据类型?如果 SIZE <= 7,我希望 _value 是一个字符。如果它 >= 8 且 <= 15,我希望它很短,如果它 <= 31,我希望它是一个整数。
最佳答案
这不是特别优雅,但是:
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
};
然后在你的类里面:
typename best_integer_type<SIZE>::type _value;
它不处理 SIZE
的负数.您的原始代码也没有,但您的文字描述说使用 char
如果SIZE <= 7
.我期待 0 <= SIZE <= 7
会做的。
关于c++ - 让模板通过指定 bitesize 在 char/short/int 之间进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9095303/