【问题标题】:Template specialization depending on type模板专业化取决于类型
【发布时间】:2015-03-04 03:44:05
【问题描述】:

我尝试使用模板元编程根据类型和其他值计算常量。

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 struct bin_size { const bins_t upper_bound = sizeof(upper_bound) == 1 ? 255:60 * number_of_bits * 10; };但我仍然想知道如何通过元编程方法解决这个问题。

标签: c++ templates gcc


【解决方案1】:

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

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

【讨论】:

  • 嗯,我把它复制到我的代码中,我得到了和以前一样的错误。
  • 您可能没有正确复制。正如您在示例中看到的,它编译得很好。至少,你明白我改变了什么吗?
  • 是的,我了解您所做的更改。我以前试过这个,但由于未知原因它失败了。我再次复制了它,现在它可以工作了。我不知道为什么它在十分钟前失败了。
【解决方案2】:

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

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

【讨论】:

    【解决方案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;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多