2015-07-21 15 views
9

喬納森Wakely的answer的這個問題Type trait to check that all types in a parameter pack are copy constructible給出了一個簡單(ISH)的方式,檢查所有的參數包擴展的變量是同一類型的 - 例如:檢查參數組對所有類型T

#include <type_traits> 

namespace detail { 
    enum class enabler {}; 
} 

template <bool Condition> 
using EnableIf = 
    typename std::enable_if<Condition, detail::enabler>::type; 

template<typename... Conds> 
struct and_ : std::true_type {}; 

template<typename Cond, typename... Conds> 
struct and_<Cond, Conds...> 
     : std::conditional<Cond::value, and_<Conds...>, 
     std::false_type>::type {}; 

template<typename... T> 
using areInts = and_<std::is_same<T,int>...>; 

template<typename... T> 
using areMySpecificClass = and_<std::is_same<T,MySpecificClass>...>; 

例如,我無法弄清楚如何擴展它,編寫一個像areTypeT這樣的模板。

我第一次嘗試偶然發現「Parameter pack'T'必須位於模板參數列表的末尾」。我最近的嘗試編譯,但如果我使用它,然後我得到替代失敗:

template<typename Target> 
template<typename... T1> 
using areT = and_<std::is_same<T1,Target>...>; 

我該如何使這項工作?

回答

4

你的語法就在一點,你並不需要兩個獨立的模板聲明,即語法定義成員模板外的類:

template<typename Target, typename... Ts> 
using areT = and_<std::is_same<Ts,Target>...>; 

static_assert(areT<int,int,int,int>::value,"wat"); 
static_assert(!areT<int,float,int,int>::value,"wat"); 

Demo

2

剛這

template<typename Type, typename... T> 
using areTypeT = and_<std::is_same<T, Type>...>;