c – 根据constexpr模式创建位掩码
发布时间:2020-12-16 03:18:36 所属栏目:百科 来源:网络整理
导读:我想实现一个模板函数,它在编译时为整数类型生成位掩码.这些掩模应基于8位模式,其中模式将连续重复以填充整数.以下示例完全符合我的要求,但在运行时: #include iostream#include type_traits#include cstringtemplatetypename Inttypename std::enable_ifst
我想实现一个模板函数,它在编译时为整数类型生成位掩码.这些掩模应基于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中运行.也许更老. 在较新版本的C中,可能有一些方法可以使这更简单.哎呀,即使在C 03中,它也可以简化. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |