我目前正在处理 SCSI 参数数据 block 。与我的 Windows PC 相比,SCSI 编号是大端的。这些数字可以是 2、3、4、6 或 8 个字节长,并存储为这些长度的 BYTE
数组。
直到现在,我都使用宏从这样的数组中获取一个小端序号。但我想想出一个真正的 C++ 方法来做这件事,所以我写了这个:
template <size_t Size>
struct ByteSwappedNumber
{
BYTE bytes[Size];
UINT64 GetValue()
{
UINT64 val = 0;
for (size_t i = 0; i < ARRAYSIZE(bytes); ++i)
{
val |= (UINT64(bytes[i]) << ((ARRAYSIZE(bytes) - i - 1) * CHAR_BIT));
}
return val;
}
};
问题是,是否可以使用模板将 GetValue
的返回类型更改为尽可能小的类型 >= sizeof(bytes)
?
我也看过 Boost Endian 库,但让它与 24 位数字一起工作似乎是不可能的。很乐意以其他方式展示。
最佳答案
我不确切地知道你想要实现什么,但是一些整数到返回类型的映射可以像下面的代码一样完成:
template<size_t N> struct return_type_impl : return_type_impl<N+1>
{
static_assert(N>=0 && N<=64, "N SHOULD BE POSITIVE AND SMALLER THAN 65");
};
template<> struct return_type_impl<64> { using type = std::int64_t; };
template<> struct return_type_impl<32> { using type = std::int32_t; };
template<> struct return_type_impl<16> { using type = std::int16_t; };
template<> struct return_type_impl<8> { using type = std::int8_t; };
template<size_t N>
using return_type = typename return_type_impl<N>::type;
int main()
{
static_assert(std::is_same<return_type<46>, std::int64_t>::value,"");
static_assert(std::is_same<return_type<15>, std::int16_t>::value,"");
}
它选择最近的可用 std::intXX_t
类型,其中 XX
大于整数模板参数 N
。根据需要进行调整。
关于c++ - 根据模板参数大小在成员函数中使用不同的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350097/