简体   繁体   中英

Template specialization depending on type

I try to compute a constant depending on a type and some other value with some template metaprogramming.

template <typename t, uint8_t number_of_bits> struct bin_size {};

template <>
struct bin_size<uint8_t, uint8_t number_of_bits> {
    const uint8_t upper_bound = 255;
};

template <>
struct bin_size<int32_t, uint8_t number_of_bits> {
    const uint8_t upper_bound = 60 * number_of_bits * 10;
};

However the compiler (arm-none-eabi-g++ (GNU Tools for ARM Embedded Processors (Arduino build)) 4.8.3 20140228 (release) [ARM/embedded-4_8-branch revision 208322] ) complains with the following errors.

test.cpp:287:52: error: template argument 2 is invalid
     struct bin_size<uint8_t, uint8_t number_of_bits> {
                                                    ^
test.cpp:292:52: error: template argument 2 is invalid
     struct bin_size<int32_t, uint8_t number_of_bits> {
                                                    ^
Error compiling.

Without the number_of_bits feature everything works out as it should. But I can not figure out how to specialize on the typename but not on the number of bits. How can this be done?

Make number_of_bits a template argument:

template <uint8_t number_of_bits>
struct bin_size<uint8_t, number_of_bits> {
    const uint8_t upper_bound = 255;
};

template <uint8_t number_of_bits>
struct bin_size<int32_t, number_of_bits> {
    const uint8 upper_bound = 60 * number_of_bits * 10;
};

The (partial) specialization should be something like:

template <uint8_t number_of_bits>
struct bin_size<uint8_t, number_of_bits> {
    const uint8_t upper_bound = 255;
};

Simply add a template parameter expecting a number and use its name in your specialization :

template <uint8_t number_of_bits>
struct bin_size<uint8_t, number_of_bits> {
    const uint8_t upper_bound = 255;
};

template <uint8_t number_of_bits>
struct bin_size<int32_t, number_of_bits> {
    const uint8_t upper_bound = 60 * number_of_bits * 10; // You forgot "_t" here.
};

By doing so, the specialization is partial and still depends on something ( number_of_bits in your case)

Here is an example : https://ideone.com/fvTa0O

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM