繁体   English   中英

C ++编译时位掩码添加

[英]C++ compile-time bitmask addition

我要添加许多位掩码(层,逻辑OR | ),但是由于它们是常量,所以我想在编译时这样做。 输入高级模板领域...

我尝试了递归:

template <uint8_t mask, uint8_t...masks>
struct MaskAdd {
    static const uint8_t value = masks | MaskAdd<masks>::value;
};

template <uint8_t mask>
struct MaskAdd {
    static const uint8_t value = mask;
};

出现以下错误:

file.cpp:3:55: error: parameter packs not expanded with ‘...’:
  static const uint8_t value = masks | MaskAdd<masks>::value;
                                                       ^
file.cpp:3:55: note:         ‘masks’
file.cpp:7:8: error: redeclared with 1 template parameter
 struct MaskAdd {
        ^
file.cpp:2:8: note: previous declaration ‘template<unsigned char mask, unsigned char ...masks> struct MaskAdd’ used 2 template parameters
 struct MaskAdd {
        ^

我还尝试了这种奇怪的语法,(可能是)对参数包上的cppreference页面有误解:

template <uint8_t...masks>
struct MaskAdd {
    static const uint8_t value = (masks | ...);
};

引发了以下错误:

file.cpp:3:43: error: expected primary-expression before ‘...’ token
     static const uint8_t value = (masks | ...);
                                           ^
file.cpp:3:43: error: expected ‘)’ before ‘...’ token

我感到解决方案在地狱的template<template<区域中的某个地方,如果有人可以解释的话,我将不胜感激。

您在此表达式中有错字:

masks | MaskAdd<masks>::value

它应该是:

mask | MaskAdd<masks...>::value
// ^ no 's'          ^ the expansion compiler was talking about

然后它将抱怨该类的重新声明,因此请提供专门化(针对单个参数):

template <uint8_t mask>
struct MaskAdd<mask> { .. };

这是我编写编译时间掩码的方法。第一个模板化参数是从右开始计数的位的位置,第二个参数是被设置为1朝左的位的数量。

template <unsigned START, unsigned RANGE>
struct Mask
{
    static const size_t val = 1 << START | Mask<START + 1, RANGE - 1>::val;
};

template <unsigned START>
struct Mask<START, 0>
{
    static const size_t val = 0;
};

如果要创建一个数字为14(0000 1110)的蒙版:

unsigned mask = Mask<1, 3>::val;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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