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?
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, "");
}
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{});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With