Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter duplicate types from tuple C++

How does one filter duplicate types from a tuple?

For example:

using Tuple = std::tuple<int, double, int, double, std::string, std::string>
using FilteredTuple = without_duplicates<Tuple>;

In which without_duplicates is implemented in such a way that it generates the following FilteredTuple type:

std::tuple<int, double, std::string>
like image 818
Andreas Loanjoe Avatar asked May 01 '19 19:05

Andreas Loanjoe


People also ask

How to remove duplicates from a tuple?

Method #1 : Using set() + tuple() This is the most straight forward way to remove duplicates. In this, we convert the tuple to a set, removing duplicates and then converting it back again using tuple().

Are there duplicates in tuples?

Formal query languages are based on mathematical relations. Thus no duplicates appear in relations.


1 Answers

#include <type_traits>
#include <tuple>

template <typename T, typename... Ts>
struct unique : std::type_identity<T> {};

template <typename... Ts, typename U, typename... Us>
struct unique<std::tuple<Ts...>, U, Us...>
    : std::conditional_t<(std::is_same_v<U, Ts> || ...)
                       , unique<std::tuple<Ts...>, Us...>
                       , unique<std::tuple<Ts..., U>, Us...>> {};

template <typename... Ts>
using unique_tuple = typename unique<std::tuple<>, Ts...>::type;

DEMO

like image 159
Piotr Skotnicki Avatar answered Sep 22 '22 20:09

Piotr Skotnicki