C ++ how to combine conditions from the standard type type_traits

For example, I want to use type T only if it is std::is_pointer<T> and std::is_const<T> .

Of course, there is an easy way:

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

But I want something like this:

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

In a standard C ++ class, something like std::and ? If not, is this some simple way to implement it with the desired functionality?

+7
c ++ c ++ 11
source share
2 answers

You can simply && combine the results of these properties and put them in std::integral_constant :

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

Or you can write a generic attribute and . Some features here :

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

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

When we get the fold expressions , you can do this:

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

Your compiler may already support this under the flag -std=c++1z , for example this .

+9
source share

With the advent of C ++ 17 conjunction and disjunction , you can easily compose for variational (number) predicates:

 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; 

And here is how you use it:

 satisfies_all_v<T, is_pointer, is_const> 

Demo

+4
source share

All Articles