问题
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