Udo Klein
Udo Klein

Reputation: 6882

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?

Upvotes: 1

Views: 112

Answers (3)

David G
David G

Reputation: 96810

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;
};

Upvotes: 3

Telokis
Telokis

Reputation: 3389

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

Upvotes: 3

Jarod42
Jarod42

Reputation: 217275

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;
};

Upvotes: 3

Related Questions