Search code examples
c++c++11templatesc++14template-meta-programming

Filter a tuple list of types given a template template predicate


I was going to ask a question, but have found an answer on my own while writing it. The question is how to filter a tuple given a template template predicate without specializing it.

Example usage:

    using tuple_list_t = std::tuple<std::string, int, none, double, char, abc, bool>;
    using tuple_found_expected_t = std::tuple<int, double, char, bool>;

    // filtering a tuple 
    using tuple_filtered_t = filter_t<tuple_list_t, std::is_fundamental>;

    static_assert(std::is_same<tuple_filtered_t, tuple_found_expected_t>(), "");

If someone have any advices or remarks about the problem, please, write an answer or a comment.


Solution

  • Sorry but your solution seems to me over-complicated. Particularly regarding the SFINAE part (why the void?).

    What about simply as follows?

    template <typename, template <typename...> class>
    struct filter;
    
    template <typename ... Ts, 
              template <typename...> class Pred>
    struct filter<std::tuple<Ts...>, Pred>
     { 
       using type = decltype(std::tuple_cat(std::declval<
          std::conditional_t<Pred<Ts>::value,
                             std::tuple<Ts>,
                             std::tuple<>>>()...));
     };
    
    template <typename Tpl, 
              template <typename...> class Pred>
    using filter_t = typename filter<Tpl, Pred>::type;