代码之家  ›  专栏  ›  技术社区  ›  SapphireSun

对于所有数据宽度,一般将uint64\u t转换为int64\u t

c++
  •  2
  • SapphireSun  · 技术社区  · 5 年前

    如何在不指定特定宽度的情况下将有符号整数和无符号整数转换为其他整数?

    例如:

    uint8_t <-> int8_t
    uint16_t <-> int16_t
    uint32_t <-> int32_t
    uint64_t <-> int64_t
    

    如果你能写下:

    uint32_t x;
    int32_t y;
    static_cast<signed>(x)
    static_cast<unsigned>(y)
    

    我认为使用这种方法可以获得类似的效果,但我认为对于相同的数据宽度使用这种方法可能会有一些语法上的好处。

    Conditional template type math

    1 回复  |  直到 5 年前
        1
  •  4
  •   Adrian Mole Chris    5 年前

    然而,我怀疑这并不是我想要的。

    事实上,你的怀疑是正确的:, static_cast<signed>(x) 是 确切地 相当于 static_cast<signed int>(x) 总是 对象的“默认”大小为 int 在给定平台上(同样, unsigned 相当于 unsigned int ).


    但是,只需做一点工作,就可以创建使用 std::make_signed 和 std::make_unsigned 类型特征结构。

    以下是此类函数的一个可能实现,其中包含一个简短的测试程序,该程序显示了不同输入类型宽度的一些推断结果类型:

    #include <type_traits> // For make_signed and make_unsigned
    
    template<typename T>
    static inline auto unsigned_cast(T s)
    {
        return static_cast<std::make_unsigned<T>::type>(s);
    }
    
    template<typename T>
    static inline auto signed_cast(T s)
    {
        return static_cast<std::make_signed<T>::type>(s);
    }
    
    
    #include <typeinfo>    // For "typeid"
    #include <iostream>    
    
    int main()
    {
        int16_t s16 = 42;
        auto u16 = unsigned_cast(s16);
        std::cout << "Type of unsigned cast is: " << typeid(u16).name() << "\n";
    
        uint64_t u64 = 39uLL;
        auto s64 = signed_cast(u64);
        std::cout << "Type of signed cast is: " << typeid(s64).name() << "\n";
        return 0;
    }