将可变参数模板参数转换为其他类型
如何将类型从可变参数模板参数转换为另一种类型?
例如:
template <typename... T>
struct single
{
std::tuple<T...> m_single;
};
template <typename... T>
struct sequences
{
single<T...> get(size_t pos)
{
// I don't know how to convert here
return std::make_tuple(std::get<0>(m_sequences)[pos]... std::get<N>(m_sequences)[pos]);
}
template <size_t Idx>
std::vector<
typename std::tuple_element<Idx, std::tuple<T...>>::type
>
get_sequence()
{
return std::get<Idx>(m_sequences);
}
std::tuple<T...> m_sequences; // std::tuple<std::vector<T...>> I don't know how to conver here
};
我想这样写:
sequences<int, double, double> seq;
single<int, double, double> sin = seq.get(10);
并且在结构中有 std::tuple
序列。并从中获得单身。
std::vector
对我来说是个坏主意,因为我需要完整的一个序列,并且很容易从 .
是否可以?
非常感谢。抱歉我的英语不好。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,这可能看起来有点矫枉过正,但是这样怎么样:据我所知,“迭代”变量的唯一选择是使用
表示法和针对简单
情况的模板专门化。因此你可以尝试这样的事情:
简单的情况:
递归的情况:
免责声明:未经测试,甚至没有编译,但我想你明白了基本的想法。至少还存在两个问题:
get()
的返回值不是单个结构体,而是一个元组链。也许您可以使用std::get<0>
递归地解开它...V
可以与T
不同。OK, this might seem a bit like overkill but how about this: As far as I know the only option to "iterate" variadics is using the
<head, tail...>
notation with a template specialization for the simple<head-only>
case.Therefore you could try something like this:
simple case:
recursive case:
Disclaimer: not tested, not even compiled, but I suppose you get the basic idea. At least two problems remain:
get()
is not your single struct but a tuple chain. Perhaps you can unchain it recursively withstd::get<0>
...V
can differ fromT
.您不仅可以将可变参数包扩展为普通列表:您还可以扩展表达式。因此,您可以将 m_sequences 设为向量元组,而不是元素元组:
您还可以使用参数包进行巧妙的处理,以从向量中选择适当的元素:
You can do more than just expand a variadic parameter pack as a plain list: you can expand an expression too. You can therefore have
m_sequences
be a tuple of vectors rather than a tuple of the elements:You can also do nifty tricks with parameter packs to pick the appropriate element from the vector: