小编jbo*_*rnl的帖子

如何:将 C++14 模板函数扩展到可变参数模板、参数

我是一名回归 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;
}
Run Code Online (Sandbox Code Playgroud)

例如,以下代码(取自运行 xeus-cling C++14 …

c++ template-meta-programming variadic-templates c++14

4
推荐指数
1
解决办法
153
查看次数