c++ - 如何获得模板参数包的最大成员?

标签 c++ templates sizeof

我的结构是这样定义的:

template<class...T> struct Data {};

如何获得sizeof(T)的最大值,以便在struct Data中使用?

最佳答案

如果您需要最大尺寸,解决方案非常简单:使用 std::max采用 std::initializer_list 的重载。从 C++14 开始它是 constexpr

constexpr std::size_t max_size = std::max({sizeof(T)...});

要处理空包,您可以添加 0 参数:

constexpr std::size_t max_size = std::max({0, sizeof(T)...});

如果需要类型本身并且可以使用 Boost,Boost.Mp11可能有帮助:

namespace mp11 = boost::mp11;

template<class T1, class T2>
struct less_sizeof : mp11::mp_bool<(sizeof(T1) < sizeof(T2))> {};

using Tm = mp11::mp_max_element<mp11::mp_list<T...>, less_sizeof>;

如果 Boost 不可用,可以使用一些简单的元编程:

template<class T, class... U>
struct max_sizeof {
    using Tm = typename max_sizeof<U...>::type;
    using type = std::conditional_t<(sizeof(Tm) < sizeof(T)), T, Tm>;
};

template<class T>
struct max_sizeof<T> {
    using type = T;
};

using Tm = typename max_sizeof<Ts...>::type;

在这两种情况下,平局被解析为具有最大 sizeof(T) 的最后一个类型。

关于c++ - 如何获得模板参数包的最大成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68879654/

相关文章:

php 简单函数中的未定义偏移量()

c# - C# 中 boolean 和 char 数据类型的 Marshal.SizeOf 和 sizeof 运算符的相反行为

C++ 是否有任何关于如何使用句柄的教程?

c++ - 从共享内存中读取字符串 C++ POSIX

C++ 继承和构造函数

c++ - C++ 中的泛型 JAVA? <X extends T> 怎么办?

c++ - 通过构造函数转换容器

c++ - 使用 SFINAE 检测编译时是否存在重载的独立函数

c++ - 如何在模板中添加 const 限定符

c - C 中 Sizeof 的行为