c – 根据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'

我知道优化器可以在上面的代码中消除整个函数调用,但我正在寻找一个带有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 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&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...