继承自std :: true_type vs static constexpr const bool成员

时间:2016-06-08 11:16:53

标签: c++

我知道这不是一个非常尖锐的问题。使用一个优于另一个是否有优势(编译时,依赖性,调试符号大小,可用性,可读性等)?

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

VS

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

相关问题......

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 >{};

1 个答案:

答案 0 :(得分:6)

继承true_type / false_type已经为您提供了相应的value成员,函数调用运算符以及对bool的隐式转换。此外,如果您将使用继承,您的类型将有资格进行标记调度,这通常比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>{})
}