Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting from std::true_type vs static constexpr const bool member

Tags:

c++

I know this is not a very pointed question. Is there an advantage (compile time, dependencies, debug symbol sizes, usability, readability etc) of using one over another?

template < typename T >
struct IsSharedPtr : std::false_type
{
};

vs

template < typename T >
struct IsSharedPtr
{
    static constexpr bool value = false;
};

A related question...

template < typename T, typename Enabler >
struct S;

template < typename T >
struct S < T, std::true_type >{};

template < typename T >
struct S < T, std::false_type >{};

vs

template < typename T, bool enabler >
struct S;

template < typename T >
struct S < T, true >{};

template < typename T >
struct S < T, false >{};
like image 558
zrb Avatar asked Jun 08 '16 11:06

zrb


1 Answers

Inheriting from true_type/false_type will already provide you with corresponding value member, function call operator and implicit conversion to bool. In addition, if you will use inheritance, your type would be eligible for tag dispatch, which is often clearer and easier than SFINAE:

namespace detail 
{
template <typename T>
void do_work(T& foo, std::true_type);

template <typename T>
void do_work(T& foo, std::false_type);
}

template <typename T>
void do_something(T& foo) 
{
    //Selects overload depending on type of IsSharedPtr<T>
    detail::do_work(foo, IsSharedPtr<T>{})
}
like image 103
Revolver_Ocelot Avatar answered Oct 18 '22 21:10

Revolver_Ocelot