简体   繁体   English

C ++模板化zip

[英]C++ templated zip

I have the following code of templated zip function: 我有以下模板化的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;
 }

and I'm trying to use it like this: 我正在尝试像这样使用它:

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);
}

getting: 得到:

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

What should I do to make it compile and execute? 我应该怎么做才能使其编译和执行?

You're not passing a type to the template list: 您没有将类型传递给模板列表:

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

Try this code 试试这个代码

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);
}

See here for a working code. 请参阅此处以获取工作代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM