我试图将std::tuple转换为std::set 。 我有以下代码
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; }编译器抱怨解压缩该行的参数包
ret.insert(std::get<Is>(t))...;我不明白这里有什么问题。
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.
最满意答案
这个:
ret.insert(std::get<Is>(t))...;不是参数包扩展的有效上下文。 不幸。 但是有办法做你想做的事:
有标准的扩展器技巧:
using expander = int[]; expander{0, (void(ret.insert(std::get<Is>(t))), 0)... };或者您可以依赖于set可以使用initializer_list构建的事实:
return std::set<ret_t>{std::get<Is>(t)...};(可能需要附加一个static_cast以确保所有元素都返回ret_t )
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)
更多推荐
发布评论