首页 > 解决方案 > 如果可能的话,我如何使用可变参数模板来制作一个并排打印多个任何类型的 std::vectors 的函数?

问题描述

我正在尝试编写一个函数 printV(),它需要一些可使用 cout 打印的内置类型的向量(可能少于六个),作为 const 引用传递并并排打印,以便 compareV(v1, v2 , v3) 将产生输出:

v1[1], v2[1], v3[1]  
v1[2], v2[2], v3[3]
v1[3], v2[3], v3[3]

这是我用来打印单个向量的函数:

template <typename T>
void printV(const std::vector<T> &vec)
{
    for (int i = 0; i < vec.size(); i++)
    {
        std::cout << i << ": " << vec[i] << std::endl;
    }
}

我想调整这个函数来并排打印多个向量。但是,我不知道是否可以执行以下操作:

template <typename... T>
void printV(const std::vector<T>... &vec)
{
     //code that expands (vec...) into vec1, vec2, vec3 etc. the part I'm unsure about

     for(int i = 0; i < vec1.size(); i++)// the size of the first vector will be the same as the other two
     {
          std::cout << i << ": " << vec1.at(i) << ", " << vec2.at(i) << ", " << vec3.at(i) << std::endl;
     }
}

我将不得不使用某种实用函数和一个中间字符串变量来解决无法在同一范围内一起访问 pramaters 的事实。 这篇 microsoft 文档文章以及“C++ 编程语言”的第 3.4.4 节建议使用递归将第一个参数与其后面的所有参数分开,并为没有参数的情况重载函数:

// From Section 3.4.4 of "The C++ Programming Language"
template<typename T, typename ... Tail>
void f(T head, Tail... tail)
{
g(head); // do something to head
f(tail...); // try again with tail
}
void f() { } // do nothing

这将阻止访问单个范围内的多个参数。我该如何解决这个问题?非常感谢任何建议或一般建议,谢谢!

标签: c++variadic-templates

解决方案


你可以这样做:

template <typename firstT, typename... T>
void printV(const std::vector<firstT>& first, const std::vector<T>& ... vec)
{
     for(int i = 0; i < first.size(); i++) 
     {
          std::cout << i << ": " << first.at(i);
          ( (std::cout << ' ' << vec.at(i)), ... );
          std::cout << std::endl;
     }
}

直播:https ://godbolt.org/z/dq5P64


推荐阅读