Ite*_*tor 2 c++ templates sizeof
我的结构定义如下:
template<class...T> struct Data {};
Run Code Online (Sandbox Code Playgroud)
怎么可能得到最大的sizeof(T),所以它可以在里面使用struct Data?
如果您需要最大的尺寸,解决方案非常简单:使用std::max需要std::initializer_list. 这是constexpr因为C ++ 14。
constexpr std::size_t max_size = std::max({sizeof(T)...});
Run Code Online (Sandbox Code Playgroud)
要处理空包,您可以添加0参数:
constexpr std::size_t max_size = std::max({0, sizeof(T)...});
Run Code Online (Sandbox Code Playgroud)
如果需要类型本身并且可以使用 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>;
Run Code Online (Sandbox Code Playgroud)
如果 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;
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,平局都被解析为具有最大sizeof(T).
如果您想要实际类型(嗯,第一个具有最大大小的类型),那么它在 C++17 及更高版本中可以非常紧凑:
#include <cstddef>
#include <algorithm>
#include <tuple>
template<class...T> struct Data {
static constexpr std::size_t biggest_idx() {
std::size_t const sizes[] { sizeof(T) ... };
return std::max_element(std::begin(sizes), std::end(sizes)) - std::begin(sizes);
}
using biggest = std::tuple_element_t<biggest_idx(), std::tuple<T...>>;
};
Run Code Online (Sandbox Code Playgroud)
只需在 constexpr 实用程序中找到索引(使用constexpr max_element),然后使用std::tuple便利来获取类型。
如果您不喜欢std::tuple在这里使用,那么您当然可以推出自己的元功能。很直接。如果您只有 C++14,您还可以编写用于手动查找最大索引的循环。
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |