【发布时间】:2020-10-14 04:28:38
【问题描述】:
我是一名回归的 C++ 程序员,已经离开这门语言好几年了(当我最后一次活跃于这门语言时,C++11 才刚刚开始获得真正的关注)。在过去的几年里,我一直在积极地用 Python 开发数据科学应用程序。作为一个恢复速度的学习练习,我决定在 C++14 中实现 Python 的 zip() 函数,现在有一个工作函数可以接受任何两个 STL(和其他一些)容器,其中包含任何类型和“zip”将它们转换为元组向量:
template <typename _Cont1, typename _Cont2>
auto pyzip(_Cont1&& container1, _Cont2&& container2) {
using std::begin;
using std::end;
using _T1 = std::decay_t<decltype(*container1.begin())>;
using _T2 = std::decay_t<decltype(*container2.begin())>;
auto first1 = begin(std::forward<_Cont1>(container1));
auto last1 = end(std::forward<_Cont1>(container1));
auto first2 = begin(std::forward<_Cont2>(container2));
auto last2 = end(std::forward<_Cont2>(container2));
std::vector<std::tuple<_T1, _T2>> result;
result.reserve(std::min(std::distance(first1, last1), std::distance(first2, last2)));
for (; first1 != last1 && first2 != last2; ++first1, ++first2) {
result.push_back(std::make_tuple(*first1, *first2));
}
return result;
}
例如,以下代码(取自 Jupyter notebook 中运行 xeus-cling C++14 内核的代码单元)
#include <list>
#include <xtensor/xarray.hpp>
list<int> v1 {1, 2, 3, 4, 5};
xt::xarray<double> v2 {6.01, 7.02, 8.03};
auto zipped = pyzip(v1, v2);
for (auto tup: zipped)
cout << '(' << std::get<0>(tup) << ", " << std::get<1>(tup) << ") ";
产生这个输出:
(1, 6.01) (2, 7.02) (3, 8.03)
我想扩展我的函数以获取任意数量的任意类型的容器,并且我花了一些时间研究可变参数模板,但令我尴尬的是,我只是没有连接这些点。我如何推广这个函数来获取任意数量的任意容器类型来保存任意数据类型?我不一定要寻找我需要的确切代码,但我确实可以使用一些帮助来了解如何在这种情况下利用可变参数模板。
此外,如果对我的代码提出任何批评,我们将不胜感激。
【问题讨论】:
标签: c++ c++14 variadic-templates template-meta-programming