Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return the largest type in a list of types?

How would I make a class template that returns the type whose sizeof is greater than the others. For example:

typename largest<int, char, double>::type;

That should return double. How would I go about doing that?

like image 422
Me myself and I Avatar asked May 29 '13 00:05

Me myself and I


2 Answers

You can accomplish this with the use of variadic template arguments and compile-time conditionals:

#include <type_traits>

template <typename... Ts>
struct largest_type;

template <typename T>
struct largest_type<T>
{
    using type = T;
};

template <typename T, typename U, typename... Ts>
struct largest_type<T, U, Ts...>
{
    using type = typename largest_type<typename std::conditional<
            (sizeof(U) <= sizeof(T)), T, U
        >::type, Ts...
    >::type;
};

int main()
{
    static_assert(
        std::is_same<largest_type<int, char, double>::type, double>::value, "");
}
like image 189
David G Avatar answered Oct 21 '22 02:10

David G


Here's a version that will pick the largest type, but breaks ties in favor of the last type:

template<bool, typename, typename>
struct pick_type;
template<typename T, typename U>
struct pick_type<true,T,U> {
    typedef T type;
};
template<typename T, typename U>
struct pick_type<false,T,U> {
    typedef U type;
};

template<typename...>
struct largest;
template<typename T>
struct largest<T> {
    typedef T type;
};
template<typename T, typename... U>
struct largest<T, U...> {
    typedef typename largest<U...>::type tailtype;
    typedef typename pick_type<
            (sizeof(T)>sizeof(tailtype)),
            T,
            tailtype
            >::type type;
};

Here's example code:

#include <iostream>
using namespace std;

void foo( double ) { cout << "double\n"; }
void foo( int ) { cout << "int\n"; }
void foo( char ) { cout << "char\n"; }
void foo( bool ) { cout << "bool\n"; }
void foo( float ) { cout << "float\n"; }


int main() {
    foo(largest<int,double,char,bool,float>::type{});
}
like image 8
Adam H. Peterson Avatar answered Oct 21 '22 02:10

Adam H. Peterson