4
\$\begingroup\$

Can the metafunction below be implemented more elegantly, with less code? What I have now is not very elegant or smartly written.

#include <type_traits>

namespace detail
{

template <typename T, typename A, typename ...B>
struct max_type
{
  typedef typename max_type<
    typename std::conditional<(sizeof(A) > sizeof(T)), A, T>::type,
    B...
  >::type type;
};

template <typename T, typename A>
struct max_type<T, A>
{
  typedef typename std::conditional<(sizeof(A) > sizeof(T)), A, T>::type type;
};

}

template <typename A, typename... B>
struct max_type
{
  typedef typename detail::max_type<A, A, B...>::type type;
};
\$\endgroup\$
3
\$\begingroup\$

How about this? It’s not all that much shorter, but IMHO quite a bit simpler:

#include <type_traits>

template <typename A, typename... B>
struct max_type
{
    typedef typename max_type<A, typename max_type<B...>::type>::type type;
};

template <typename A>
struct max_type<A>
{
    typedef A type;
};

template <typename A, typename B>
struct max_type<A,B>
{
    typedef typename std::conditional<(sizeof(A) > sizeof(B)), A, B>::type type;
};
\$\endgroup\$
  • \$\begingroup\$ Nice, even though I've really wanted a bit less code :) \$\endgroup\$ – user1095108 Jul 24 '13 at 6:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.