模板专业化取决于类型

时间:2015-03-03 16:48:00

标签: c++ templates gcc

我尝试使用某些模板元编程来计算一个常量,具体取决于类型和其他值。

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

然而编译器(arm-none-eabi-g ++(用于ARM嵌入式处理器的GNU工具(Arduino构建))4.8.3 20140228(发布)[ARM / embedded-4_8-branch revision 208322] 抱怨以下错误。

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.

如果没有number_of_bits功能,一切都会正常运行。但我无法弄清楚如何专注于typename而不是bit的数量。怎么办呢?

3 个答案:

答案 0 :(得分:3)

使number_of_bits成为模板参数:

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

答案 1 :(得分:3)

(部分)专业化应该是这样的:

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

答案 2 :(得分:3)

只需添加一个期望数字的模板参数,并在您的专业化中使用其名称:

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

通过这样做,专业化是部分的,仍然取决于某些事情(在你的情况下number_of_bits

以下是一个示例:https://ideone.com/fvTa0O