C++模板化的zip

C++ templated zip

本文关键字:zip C++      更新时间:2023-10-16

我有以下模板化zip函数的代码:

template< typename T1, typename T2, typename R, R F( const T1, const T2)>
 inline std::vector< R> zip( const std::vector< T1> & v1, const std::vector< T2> & v2) {
     if( v1.size() != v2.size())
         throw exception( "Bad length!");
     typename std::vector< T2>::const_iterator it2 = v2.begin();
     std::vector< R> res;
     for( typename std::vector< T1>::const_iterator it1 = v1.begin();
                                                    it1!= v1.end();
                                                  ++it1)
     {
         res.push_back( F( *it1, *it2));
       ++it2;
     }
     return res;
 }

我试着这样使用它:

class C {
public:
    static  C* foo( const C* c1, const C* c2) {
                return new C;
            }
};
std::vector< C*>  sum( const std::vector< C*> &v1, const std::vector< C*> &v2)
{
    return zip< C*, C*, C*, C::foo>( v1, v2);
}

获取:

error: could not convert template argument 'C::foo' to 'C* (*)(C*, C*)'

我应该怎么做才能使它编译和执行?

您没有将类型传递到模板列表:

zip< C*, C*, C*, C::foo>( v1, v2);
                 ^^^^^^

试试这个代码

template< typename T1, typename T2, typename R, typename F>
inline std::vector<R> zip(const std::vector<T1> & v1,
                          const std::vector<T2> & v2, F f) {
     //...
     res.push_back( f( *it1, *it2));
     //...
}
//...
std::vector<C*>  sum(const std::vector< C*> &v1, const std::vector< C*> &v2)
{
    return zip< C*, C*, C*>( v1, v2, C::foo);
}

有关工作代码,请参阅此处。