我的位流类中有以下方法(广义上讲):
class BitStream
{
void StoreBits( unsigned int data, unsigned int numBits );
public:
template<typename T>
void WriteType( T value ) { StoreBits( value, sizeof(T) * 8 ) );
template<>
void WriteType( float value ) { StoreBits( *(unsigned int*)&value, sizeof(float) * 8 ) );
};
有人在WriteType上抛出了一个强类型的枚举类,显然该枚举不会自动转换为无符号整数。
我该怎么做才能写出使用相同函数命名来处理所有枚举情况的专业化程序?
这是一个琐碎的问题-我将枚举类实例抛出到我必须处理的许多其他BitStream成员方法上,例如ReadType,StreamType(读或写),SmallestRangeWrite <Min,Max>()等。
我有C ++ 17支持。我知道这里有std :: is_enum,但是我如何在这里专门研究它,尤其是在编译时?
我能以某种方式写:
template<typename T>inline void BitStream::WriteType( T value )
{
if (type_is_enum())
StoreEnum<T>(value)
else
StoreBits( value, sizeof(T) * 8 ) );
}
我需要确保T为枚举时,不会编译StoreBits方法。仅在运行时避免使用分支是不够的。
测试一下类型是否为枚举,以及是否不能转换为u32
。这使您可以区分正常enum
和enum class
。如果它是一个枚举但不能转换为u32
,则它是enum class
:
template<typename T>
inline void BitStream::WriteType(T value)
{
if constexpr (std::is_enum_v<T> && !std::is_convertible_v<T, u32>)
// enum class
StoreEnum<T>(value)
else
// normal enum or other type that is convertible to u32
StoreBits(value, sizeof(T) * 8 ));
}
由于您的模板StoreEnum
和StoreBits
函数模板不能同时使用两者,因此您需要在if constexpr
此处使用以避免在编译时进行类型检查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句