c++ - 模板特化取决于类型

标签 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++ (GNU Tools for ARM Embedded Processors (Arduino build)) 4.8.3 20140228 (release) [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 功能,一切都会按预期进行。但是我不知道如何专注于类型名而不是位数。如何做到这一点?

最佳答案

只需添加一个需要数字的模板参数,并在您的特化中使用它的名称:

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

关于c++ - 模板特化取决于类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28837309/

相关文章:

c - BST中序遍历中的Seg Fault

c++ - 了解 Visual Studio 2010 中的此错误 (LNK 2019)

c++ - RAII 类的通用命名约定是什么?

c++ - 使用流模板以避免复制代码会产生 "error C4430: missing type specifier - int assumed"

c++ - 这是单例模式的正确实现吗?

c++ - gcc 如何优化这个循环?

gcc 内联 asm bug - 忽略参数

C++ SEH - EXCEPTION_DISPOSITION 枚举和 __except() 过滤器表达式之间的相关性

c++ - 在 C++ Builder 中使用编码写入文件

C++ 自定义分配器