将std :: tuple转换为std :: set(Converting a std::tuple to a std::set)

编程入门 行业动态 更新时间:2024-10-23 17:26:21
将std :: tuple转换为std :: set(Converting a std::tuple to a std::set)

我试图将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)

更多推荐

本文发布于:2023-07-16 07:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1125495.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   tuple   std   set   Converting

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!