我想实现一个模板函数,它在编译时为整数类型生成位掩码。这些掩码应基于 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'
我知道优化器可以消除上面代码中的整个函数调用,但我正在寻找 c++14 的 constexpr
解决方案并可选择使用 c++11 .
最佳答案
凭直觉,我会制作一个字节转发器:
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/