c++ - 基于模式创建位掩码作为 constexpr

标签 c++ c++11 bit-manipulation c++14 constexpr

我想实现一个模板函数,它在编译时为整数类型生成位掩码。这些掩码应基于 8 位模式,其中模式将连续重复以填充整数。以下示例完全符合我的要求,但在运行时:

#include <iostream>
#include <type_traits>
#include <cstring>

template<typename Int>
typename std::enable_if<std::is_integral<Int>::value, Int>::type
make_mask(unsigned char pattern) {
    Int output {};
    std::memset(&output, pattern, sizeof(Int));
    return output;
}

int main() {
    auto mask = make_mask<unsigned long>(0xf0);
    std::cout << "Bitmask: '" << std::hex << mask << "'" << std::endl;
}

上面代码的输出是:

Bitmask: 'f0f0f0f0f0f0f0f0'

我知道优化器可以消除上面代码中的整个函数调用,但我正在寻找 constexpr 解决方案并可选择使用 .

最佳答案

凭直觉,我会制作一个字节转发器:

template<class Int, int count, int byte>
struct byte_repeater;

template<class Int, int byte>
struct byte_repeater<Int, 1, byte> {
    static const Int value = byte;
};

template<class Int, int count, int byte>
struct byte_repeater {
    static const Int value = (byte_repeater<Int, count-1, byte>::value << CHAR_BIT) | byte;
};

易于使用的界面:

template<class Int, int mask> 
struct make_mask {
    static const Int value = byte_repeater<Int, sizeof(Int), mask>::value;
};

这适用于 C++03。甚至更老。 Compilation Here .

在较新版本的 C++ 中,可能有一些方法可以简化此操作。哎呀,即使在 C++03 中,它也可能会被简化。

关于c++ - 基于模式创建位掩码作为 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45225925/

相关文章:

c++ - 使用 G++ 强制链接到 pthread

c++ - 转换 Classname::FunctionName( Para1, Para2 ) 中的符号

c++ - DirectX11 深度值只有 0 和 1

c++ - 有没有办法在容器中存储不同的函数指针类型

C++ 迭代器取消引用和前缀递增/递减样式? *--Iter ok 风格明智吗?

c++ - 从参数包中获取 typedef

c - 我如何操纵位从0x00到0x34,以便创建由这些值表示的卡座

matlab - 加快处理较大的二进制文件

c - 找到下一个除以 8 的数字?

c++ - 为什么在 C++ 中对可变变量使用引用