Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

let template choose between char/short/int by specifiying bitsize?

Tags:

c++

templates

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.

like image 466
Markus Avatar asked Feb 01 '12 11:02

Markus


1 Answers

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.

like image 188
Steve Jessop Avatar answered Oct 11 '22 19:10

Steve Jessop