从可变参数类型列表中获取最大类型

时间:2014-10-18 17:59:52

标签: c++ templates c++11 variadic-templates c++14

我试图从可变参数模板类型列表中获取最大类型。我得到了意想不到的结果:

// 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的数字。

1 个答案:

答案 0 :(得分:9)

类型应该是T1中较大的一个,是剩余类型中最大的类型,而不是T1BiggestHelper</*...*/>(这是一个空结构)中的较大者。此外,对于记录,列表中最大的类型几乎肯定是std::string,而不是double

template<typename T1, typename T2, typename... TArgs> 
struct BiggestHelper<T1, T2, TArgs...>
{
    using Type = Bigger<T1, typename BiggestHelper<T2, TArgs...>::Type>;
                          //^^^^^^^^^                           ^^^^^^
};

Demo