微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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中,它也可以简化.

原文地址:https://www.jb51.cc/c/111907.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐