I've got something like this:
template<int SIZE>
struct bin {
private:
public:
struct {
int _value : SIZE;
};
}
Is it possible to change the datatype of _value depending on SIZE? If SIZE is <= 7, I want _value to be a char. If it is >= 8 and <= 15, I want it to be short and if it is <= 31, I want it to be an integer.
This isn't especially elegant, but:
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
};
Then in your class:
typename best_integer_type<SIZE>::type _value;
It doesn't deal with negative numbers for SIZE
. Neither does your original code, but your text description says to use char
if SIZE <= 7
. I expect 0 <= SIZE <= 7
will do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With