[英]Filter the tuple types with templates in C++
I need to check the types of the tuple with type traits.我需要检查具有类型特征的元组的类型。 And if the type is appropriate it should stay, if it is not its continues.
如果类型合适,它应该保留,如果不是它继续。
For example:例如:
using TUPLE = tuple<int, float,char, short, string, double, float>;
using TUPLE_INTEGRAL = filter_types_t<is_integral<void>, TUPLE>;
TUPLE_INTEGRAL --> tuple<int, char, short>
Up to now, ı did something like this,到目前为止,我做了这样的事情,
template <typename Pred, typename Tuple> struct filter_types;
template <typename t_Predicate, typename ...Ts>
struct filter_types<t_Predicate, std::tuple<Ts...>>
{
template<class E>
using t_filter_impl = std::conditional_t<
t_Predicate<E>::value,
std::tuple<E>, std::tuple<>>;
using filter_types_t = decltype(std::tuple_cat(std::declval<t_filter_impl<Ts>>()...));
};
But it's not compiling and gives an error.但它没有编译并给出错误。
Your code was almost correct.您的代码几乎是正确的。 With these 2 things changed it works:
改变了这 2 件事,它就可以工作了:
t_Predicate
needs to be a template template
type since it is used as a template in the implementation. t_Predicate
需要是template template
类型,因为它在实现中用作模板。 Here is my working version:这是我的工作版本:
#include <tuple>
#include <string>
template <template<typename> typename t_Predicate, typename ...Ts> struct filter_types;
template <template<typename> typename t_Predicate, typename ...Ts>
struct filter_types<t_Predicate, std::tuple<Ts...>>
{
template<class E>
using t_filter_impl = std::conditional_t<
t_Predicate<E>::value,
std::tuple<E>, std::tuple<>>;
using type = decltype(std::tuple_cat(std::declval<t_filter_impl<Ts>>()...));
};
template <template<typename> typename t_Predicate, typename ...Ts>
using filter_types_t = typename filter_types<t_Predicate, Ts...>::type;
using TUPLE = std::tuple<int, float,char, short, std::string, double, float>;
using TUPLE_INTEGRAL = filter_types_t<std::is_integral, TUPLE>;
static_assert(std::is_same_v<TUPLE_INTEGRAL, std::tuple<int, char, short>>);
static_assert(! std::is_same_v<TUPLE_INTEGRAL, std::tuple<int, float, char, short>>);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.