Check if the type in the parameter package of the variational pattern passed

I heard somewhere that using the new C ++ 1z syntax, it’s really easy to check if the type in the parameter package of the variational template passed - apparently, you can do this using code that is almost on the same line. It's true? What are these features? (I tried to look at bend expressions, but I don’t see how to use them in this problem ...)

Here is how I solved the problem in C ++ 11 for reference:

#include <type_traits> template<typename T, typename ...Ts> struct contains; template<typename T> struct contains<T> { static constexpr bool value = false; }; template<typename T1, typename T2, typename ...Ts> struct contains<T1, T2, Ts...> { static constexpr bool value = std::is_same<T1, T2>::value ? true : contains<T1, Ts...>::value; }; 
+5
source share
1 answer

You are looking for std::disjunction . It is listed in N4564 [meta.logical].

 #include <type_traits> template<typename T, typename... Ts> constexpr bool contains() { return std::disjunction_v<std::is_same<T, Ts>...>; } static_assert( contains<int, bool, char, int, long>()); static_assert( contains<bool, bool, char, int, long>()); static_assert( contains<long, bool, char, int, long>()); static_assert(not contains<unsigned, bool, char, int, long>()); 

Live demo


Or adapted to struct

 template<typename T, typename... Ts> struct contains : std::disjunction<std::is_same<T, Ts>...> {}; 

Or using folding expressions

 template<typename T, typename... Ts> struct contains : std::bool_constant<(std::is_same<T, Ts>{} || ...)> {}; 

Live demo

+13
source

Source: https://habr.com/ru/post/1237441/


All Articles