2015-09-11 12 views
7

Na przykład chcę użyć typu T tylko jeśli jest to std::is_pointer<T> i std::is_const<T>.C++ jak łączyć warunki z type_traits standard way

Oczywiście, istnieje prosty sposób tak:

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

Ale chcę coś takiego:

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

jest w C++ standardowych klas coś jak std::and? Jeśli nie, czy jest to prosty sposób na jego wdrożenie z pożądaną funkcjonalnością?

Odpowiedz

9

można po prostu && razem wyniki cech i umieścić je w std::integral_constant:

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

Albo można napisać rodzajowe cechę and. Niektóre możliwości z here:

Opcja 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>> 

Opcja 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>> 

Kiedy dotrzemy fold expressions będziesz w stanie to zrobić:

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

Twój kompilator może już to obsługiwać pod flagą -std=c++1z, taką jak this.

4

Wraz z pojawieniem się C++ 17 conjunction i disjunction można łatwo komponować dla zmiennej liczbie argumentów (ilość) predykaty:

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; 

I to jak chcesz go używać:

satisfies_all_v<T, is_pointer, is_const> 

Demo