c++ - sizeof(T) 值的标准类型特征

标签 c++ c++11 c++-standard-library

C++11 标准指定了一个类型特征 std::alignment_of<T>它只返回 alignof(T) 的值.

sizeof 是否有类似的特征?运算符(operator)?我只是遗漏了它,还是只是在标准中遗漏了它,或者是否有一些模糊的技术原因未指定它?

显然创建这样一个特征是微不足道的,但我无法想象在引入 std::alignment_of 时不会考虑它.

对于上下文,我有一个自定义类型特征,当应用于类型列表时,我用它来获取单个特征的最大值。

template <template<class> class Trait, typename F, typename... T>
struct trait_max
  : std::integral_constant<decltype(Trait<F>::value),
      (Trait<F>::value > trait_max<Trait, T...>::value) ? Trait<F>::value : trait_max<Trait, T...>::value>
{ };
template <template<class> class Trait, typename F>
struct trait_max<Trait, F>
  : std::integral_constant<decltype(Trait<F>::value), Trait<F>::value>
{ };

当你需要知道一组类型的最大值时,这个特性非常方便,如下所示:

auto max_align = traits_max<std::alignment_of, int, float, std::string>::value;
auto max_size = traits_max<std::size_of, int, float, std::string>::value; // doesn't exist

最佳答案

std::alignment_of在 C++11 中不是新的。它在 2007 年作为 TR1 的一部分添加(连同 <type_traits> 的其余部分)。TR1 的 <type_traits>Boost TypeTraits 批发复制, 它提供了 alignment_of只是因为在 2005 年没有标准的方法来获得该值。

当然,在 2005 年, 有一种方法可以获取类型的大小 T ;它被拼成了sizeof(T)自古以来。这就是为什么 size_of<T>不在 Boost TypeTraits 中,这就是它在 2007 年没有被复制到 TR1 中的原因,这就是它没有被继承到 C++11 中的原因。 p>

截至 2011 年,还有一种标准方法来获取类型的对齐方式 T ;它拼写为alignof(T) . 2011 年之前的构造 std::alignment_of<T>::value不必要的冗长,你几乎肯定不应该再使用它,除非你担心 2011 年之前实现的可移植性。

我相信编写示例代码的最惯用的方式是

size_t max_align = std::max({alignof(int), alignof(float), alignof(std::string)});
size_t max_size = std::max({sizeof(int), sizeof(float), sizeof(std::string)});

一旦 C++14 推出,std::max将变为 constexpr ,因此这将在编译时计算并可用于模板元编程。但是 C++11 的 suckiness std::max是一个完全独立的问题,与您的问题无关。 :)

编辑:这是一个constexpr_max在今天的 C++11 中有效。不幸的是 C++11 的 std::initializer_list不能用于 constexpr语境; C++14 也在解决这个问题。

template<typename T> constexpr T constexpr_max(T t, T u) {
    return t > u ? t : u;
}

template<typename T, typename... TT> constexpr T constexpr_max(T t, TT... ts) {
    return constexpr_max(t, constexpr_max(ts...));
}

关于c++ - sizeof(T) 值的标准类型特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19019832/

相关文章:

c++ - boost::lambda::if_then 用于 copy_if

c++ - 如果使用全局函数,则 type_trait 的成员会失败

c++ - 我可以在 c++17 代码中使用用 c++11 开发的库吗?

c++ - C++11 是否强制 pow(double, int) 使用较慢的 pow(double, double)?

c++ - 在 std::accumulate 中使用变异函数

C++ LogIn.exe 在终端中崩溃

c++ - 将 VARIANT 转换为...?

c++ - 为什么 C++ 的 64 位整数扩展名为 "long long"?

c++ - 在编译时选择使用模板调用的函数

c++ - Visual C++ 标准库关键字