Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;模板拉链_C++_Templates_Zip - Fatal编程技术网

C++ C++;模板拉链

C++ C++;模板拉链,c++,templates,zip,C++,Templates,Zip,我有以下模板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())

我有以下模板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;
 }

我应该如何使其编译和执行?

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

zip< C*, C*, C*, C::foo>( v1, v2);
                 ^^^^^^
zip(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);
}
模板
内联std::vector zip(const std::vector&v1,
常数std::向量&v2,F){
//...
res.push_back(f(*it1,*it2));
//...
}
//...
标准::向量和(常数标准::向量&v1,常数标准::向量&v2)
{
返回zip(v1,v2,C::foo);
}

有关工作代码,请参阅。

C*
const C*
是不同的类型。谢谢您,无论是这样,还是建议使用M.M的方式。在回答中,此错误已消失。使用此非类型模板参数一切正常。问题出在
foo
函数中,该函数是用
const C*
参数声明的。看,我想我会像M.建议的那样(把函数作为参数)。在我看来,在这种情况下更合适。但是,是的,康斯特也有同样的老问题。谢谢你们两位!请注意,
R
可以推导(在C++11中:
decltype(std::result\u of::type)
),因此您可以直接调用
zip(v1,v2,C::foo)
。谢谢您的建议,@Jarod42。遗憾的是,我不能在我的项目中使用C++11,但这确实是一个好主意。
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);
}