我的结构是这样定义的:
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/