如何在C ++ 17中创建从可变参数模板推导的向量类型的元组? [英] How to create a tuple of vectors of type deduced from a variadic template in C++17?

查看:87
本文介绍了如何在C ++ 17中创建从可变参数模板推导的向量类型的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一个收集类,该收集类将元组的向量转换为向量的元组(本质上是AOS到SOA的转换).此代码适用于两个模板类的示例.我试图通过使用可变参数模板使其更通用.为此,我需要为成员变量 m_col 创建类型.在C ++ 17中,是否可以将元组转换为向量的元组?因此,此示例中的成员方差 m_col 的类型将根据模板类型自动生成.

I have implemented a collection class that converts a vector of tuples to a tuple of vectors (it is essentially an AOS to SOA conversion). This code works for this example of two template classes. I was trying to make it more generic by using variadic templates. In order to do that I need to create the type for the member variable m_col. In C++17, is it possible to convert a tuple to a tuple of vectors? So the type of the member variance m_col in this example will be generated automatically from template types.

template<class T1, class T2>
class Collection
{
    std::tuple<std::vector<T1>, std::vector<T2>> m_col;

public:
    void addRow(const std::tuple<T1, T2>& data)
    {
        std::get<0>(m_col).push_back(std::get<0>(data));
        std::get<1>(m_col).push_back(std::get<1>(data));
    } 

    void show()
    {
        std::cout << std::get<0>(m_col1).size() <<std::endl;
    }
};


int main()
{
    using data_t = std::tuple<int, double>;
    data_t data{1,1.0};
    using col_t = Collection<int, double>;
    col_t col;
    col.addRow(data);    
    col.show();
}

推荐答案

您正在使用C ++ 17,所以...使用模板折叠和一些 std :: apply()怎么办?

You're using C++17 so... what about using template folding and some std::apply()?

我的意思是

template <typename ... Ts>
class Collection
 {
   private:
      std::tuple<std::vector<Ts>...> m_col;

   public:
      void addRow (std::tuple<Ts...> const & data)
       {
          std::apply([&](auto & ... vectors){
                     std::apply([&](auto & ... values){
                                (vectors.push_back(values), ...);},
                                data); },
                     m_col);        
       } 

      void show () const
       {
         std::apply([](auto & ... vectors){
             ((std::cout << vectors.size() << '\n'), ...);}, m_col);
       }
 };

这篇关于如何在C ++ 17中创建从可变参数模板推导的向量类型的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆