2016-06-08 36 views
5

我知道這不是一個非常尖銳的問題。是否有優勢(編譯時間,依賴關係,調試符號大小,可用性,可讀性等)使用一個優先?繼承自std :: true_type vs static constexpr const布爾成員

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

回答

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>{}) 
} 
+0

注意你也可以派遣上第二個模板參數,這可能是有點嚴格,因爲類型(特徵)轉換不涉及選擇功能。 – rubenvb