c++ - 根据模板参数大小在成员函数中使用不同的返回类型

标签 c++ templates visual-c++ endianness

我目前正在处理 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,"");
}

Demo on Coliru

它选择最近的可用 std::intXX_t 类型,其中 XX 大于整数模板参数 N。根据需要进行调整。

关于c++ - 根据模板参数大小在成员函数中使用不同的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350097/

相关文章:

c++ - 将模板参数传递给嵌套结构

C++ 专门化派生类中的继承模板

c++ - 低级键盘钩子(Hook) : differentiate between key codes

c++ - 在Leetcode上提交解决方案时出现堆栈缓冲区溢出错误

c++ - 如何在 VS 代码中为 Bazel 项目启用 C++ 智能感知?

c++ - 将外部库添加到 cmake 项目

c++ - Cocos2dx 动画(不使用过时的方法)

c++ - 如果一个函数类型只依赖于它自己的模板参数,它是否依赖于它?

c++ - 在 C++ 中将 UTF8 字符串转换为 UTF16 字符串

c++ - 模板函数类型推导和运算符<<