ssb
ssb

Reputation: 7502

Converting a std::tuple to a std::set

I am trying to convert a std::tuple to a std::set. I have the following code

template <typename... T>
auto to_set(std::tuple<T...> const &t) {
  return to_set_helper(t, std::index_sequence_for<T...>{});
}

template <typename T, size_t... Is>
auto to_set_helper(T&& t, std::index_sequence<Is...>) {
  using set_t = typename std::tuple_element<0, 
                      typename std::remove_reference<T>::type>::type;
  std::set<set_t> ret;
  ret.insert(std::get<Is>(t))...;
  return ret;
}

The compiler complains about unpacking the parameter pack for the line

ret.insert(std::get<Is>(t))...;

I don't see what is wrong here.

Upvotes: 1

Views: 290

Answers (1)

Barry
Barry

Reputation: 303537

This:

ret.insert(std::get<Is>(t))...;

is not a valid context for parameter pack expansion. Unfortunately. But there are ways to do what you want to do:

There's the standard expander trick:

using expander = int[];
expander{0,
    (void(ret.insert(std::get<Is>(t))), 0)...
    };

Or you can just rely on the fact that set can be constructed with an initializer_list:

return std::set<ret_t>{std::get<Is>(t)...};

(which may need a static_cast attached to it to ensure that all the elements give back a ret_t)

Upvotes: 2

Related Questions