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 替代方案?
最佳答案
您可以制作自己的安全版本:
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!
它与 sizeof
具有相同的语义,但会产生一个 int
,同时确保转换不会溢出。
关于c++ - Qt中是否有签名的 `sizeof`替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53757830/