【问题标题】:Is there a signed `sizeof` alternative in QtQt 中是否有签名的“sizeof”替代方案
【发布时间】:2018-12-13 08:33:26
【问题描述】:

Qt 容器的大小返回(签名)int。我们知道在 Qt 中,更多的是使用 int 而不是无符号类型 size_t 来进行算术运算而不需要强制转换。见Why does Qt use a signed int type for its container classes & Why QVector.size() returns int

由于语言关键字sizeof 返回size_t 类型,是否有Qt 替代方案?

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    您可以制作自己的安全版本:

    template<std::size_t s>
    constexpr int safeIntCast()
    {
        static_assert(s <= std::numeric_limits<int>::max(), "Type too large for ssizeof()!");
        return static_cast<int>(s);
    }
    
    #define ssizeof(x) safeIntCast<sizeof(x)>()
    
    /// Usage
    
    static_assert(ssizeof(int) == 4);
    static_assert(ssizeof(1.0) == 8);
    
    static_assert(ssizeof(std::declval<int>()) == 4);
    static_assert(ssizeof(int[1000000000000]) > 4); // Conversion problem is caught!
    

    Demo

    它与sizeof 具有相同的语义,但在确保转换不会溢出的同时产生int

    【讨论】:

      【解决方案2】:

      正确的答案是这是不可能的。 std::size_t 可以是std::uintmax_t,这意味着即使是最大的符合标准的类型std::intmax_t 也不能保存std::size_t 的所有值。

      在大多数情况下,您不必担心。在大多数情况下,int(或long long)将保持对象的大小,因此您可以将其转换为:static_cast&lt;long long&gt;(sizeof(T))。如果您正在做指针运算,请考虑使用std::ptrdiff_t,或者不使用sizeof 而使用end() - begin()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-02
        • 2017-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多