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/