How to filter duplicate types from tuple C++

前端 未结 4 1979
遇见更好的自我
遇见更好的自我 2020-12-17 18:36

How does one filter duplicate types from a tuple?

For example:

using Tuple = std::tuple
usi         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-17 18:41

    Piotr's code is very concise and should be prefered. Here an extended version for general variadic templated classes which works on C++17 (e.g. std::variant or custom containers):

    #include 
    
    // end of recursive call: tuple is forwared using `type`
    template 
    struct unique_impl {using type = T;};
    
    // recursive call: 1. Consumes the first type of the variadic arguments, 
    //                    if not repeated add it to the tuple.  
    //                 2. Call this again with the rest of arguments
    template  class Tuple, typename... Ts, typename U, typename... Us>
    struct unique_impl, U, Us...>
        : std::conditional_t<(std::is_same_v || ...)
                           , unique_impl, Us...>
                           , unique_impl, Us...>> {};
    
    // forward definition
    template 
    struct unique_tuple;
    
    // class specialization so that tuple arguments can be extracted from type
    template class Tuple, typename... Ts>
    struct unique_tuple> : public unique_impl, Ts...> {};
    

    Live Demo

    If you need C++11 you just need to replace the fold expression (std::is_same_v || ...) to use a self-made disjunction<...> (see cppreference possible implementation).

提交回复
热议问题