dimanche 31 mai 2015

Metaprogramming coding style

Is there any pros and cons when making a choise between two following approaches to express type trait?

#include <type_traits>

template< typename first, typename ...rest >
struct are_same;

template< typename last >
struct are_same< last >
        : std::true_type
{

};

template< typename next, typename ...rest >
struct are_same< next, next, rest... >
        : are_same< next, rest... >
{

};

template< typename first, typename second, typename ...rest >
struct are_same< first, second, rest... >
        : std::false_type
{

};

static_assert(are_same< int, int, int >::value);
static_assert(!are_same< int, char, int >::value);

another approach:

template< typename first, typename ...rest >
struct are_same;

template< typename last >
struct are_same< last > 
{

    static constexpr bool value = true;

};

template< typename next, typename ...rest >
struct are_same< next, next, rest... > 
{

    static constexpr bool value = are_same< next, rest... >::value;

};

template< typename first, typename second, typename ...rest >
struct are_same< first, second, rest... >
{

    static constexpr bool value = false;

};

static_assert(are_same< int, int, int >::value);
static_assert(!are_same< int, char, int >::value);

First approach allows me to write static_assert(!are_same< int, char, int >{}); instead of verbose static_assert(!are_same< int, char, int >::value);, but is there an issue WRT compile time? Generally speaking, I mean much more complex metaprogramming statements.

Aucun commentaire:

Enregistrer un commentaire