从可变参数类型列表中获取最大的类型 [英] Getting the biggest type from a variadic type list
本文介绍了从可变参数类型列表中获取最大的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从可变参数模板类型列表中获取最大的类型.我得到了意外的结果:
I'm trying to get the biggest type from a variadic template type list. I'm getting unexpected results:
// Bigger between two types
template<typename T1, typename T2>
using Bigger = std::conditional_t<sizeof(T1) >= sizeof(T2), T1, T2>;
// Recursion helper
template<typename...>
struct BiggestHelper;
// 2 or more types
template<typename T1, typename T2, typename... TArgs>
struct BiggestHelper<T1, T2, TArgs...>
{
using Type = Bigger<T1, BiggestHelper<T2, TArgs...>>;
};
// Exactly 2 types
template<typename T1, typename T2>
struct BiggestHelper<T1, T2>
{
using Type = Bigger<T1, T2>;
};
// Exactly one type
template<typename T>
struct BiggestHelper<T>
{
using Type = T;
};
template<typename... TArgs>
using Biggest = typename BiggestHelper<TArgs...>::Type;
下面是结果示例:
sizeof(double) -> 8
sizeof(Biggest<int, char, long, std::string, long long, double>) -> 4
我做错了什么?我希望返回大于4的数字.
What am I doing wrong? I expect a number bigger than 4 to be returned.
推荐答案
该类型应该是 T1
中的较大者,并且是其余类型中最大的类型,而不是 T1中的较大类型
和 BiggestHelper</*...*/& gt;
(这是一个空结构).另外,根据记录,列表中最大的类型几乎可以肯定是 std :: string
,而不是 double
.
The type should be the bigger of T1
and the biggest of the remaining types, not the bigger of T1
and BiggestHelper</*...*/>
(which is an empty struct). Also, for the record, the biggest type in your list is almost certainly std::string
, rather than double
.
template<typename T1, typename T2, typename... TArgs>
struct BiggestHelper<T1, T2, TArgs...>
{
using Type = Bigger<T1, typename BiggestHelper<T2, TArgs...>::Type>;
//^^^^^^^^^ ^^^^^^
};
演示.
这篇关于从可变参数类型列表中获取最大的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文