Getting the biggest type from a variadic type list

ぃ、小莉子 提交于 2019-12-24 00:38:14

问题


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;

Here's an example of the results:

sizeof(double) -> 8
sizeof(Biggest<int, char, long, std::string, long long, double>) -> 4

What am I doing wrong? I expect a number bigger than 4 to be returned.


回答1:


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>;
                          //^^^^^^^^^                           ^^^^^^
};

Demo.



来源:https://stackoverflow.com/questions/26442859/getting-the-biggest-type-from-a-variadic-type-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!