2015-09-11 4 views
7

たとえば、タイプTは、std::is_pointer<T>std::is_const<T>の場合にのみ使用します。C++ type_traitsからの条件結合方法標準

もちろん、そこにこのような単純な方法です:

template <typename T> 
void f(T t, std::true_type, std::true_type) {} 
template <typename T> 
void f(T t) 
{ 
    f(t, std::is_pointer<T>{}, std::is_const<T>{}); 
} 

は、しかし、私はこのような何かしたい:

template <typename T> 
void f(T t, std::true_type) {} 
template <typename T> 
void f(T t) 
{ 
    f(t, std::and<std::is_pointer<T>, std::is_const<T>>{}); 
} 

をC++標準クラスでstd::andのようなものですか? いいえ、それを実装する簡単な方法は何ですか?

答えて

9

あなたはできるだけで一緒に&&形質の結果とstd::integral_constantに入れ:

std::integral_constant<bool, 
         std::is_pointer<T>::value && std::is_const<T>::value> 

それとも、一般的な特性andを書くことができます。 hereからのいくつかの可能性:

オプション1

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

//usage 
and_<std::is_pointer<T>, std::is_const<T>> 

はオプション2

template<bool...> struct bool_pack; 
template<bool... bs> 
using and_ = std::is_same<bool_pack<bs..., true>, bool_pack<true, bs...>>; 

//usage 
and_<std::is_pointer<T>, std::is_const<T>> 

我々はfold expressionsを取得すると、あなたがこれを行うことができるでしょう:

template<typename... Args> 
using and_ = std::integral_constant<bool, (Args::value && ...) >; 

あなたのコンパイラはthisのように-std=c++1zフラグの下で既にこれをサポートしているかもしれません。 C++ 17 conjunctionの出現により

4

disjunctionあなたが簡単に(の数)は、述語可変長のために作曲ができます

template <class T, template <class> class... Ps> 
constexpr bool satisfies_all_v = std::conjunction<Ps<T>...>::value; 

template <class T, template <class> class... Ps> 
constexpr bool satisfies_any_v = std::disjunction<Ps<T>...>::value; 

そして、これはあなたがそれを使用したい方法です:

satisfies_all_v<T, is_pointer, is_const> 

Demo