c – 包装模板函数和<未解析的重载函数类型
发布时间:2020-12-16 10:25:31 所属栏目:百科 来源:网络整理
导读:我的包装功能有问题. template typename Iter,typename SomeFunction void wrap(Iter first,Iter last,SomeFunction someFunction){ someFunction(first,last);} 我想像这样使用它: template typename Itervoid fill5(Iter first,Iter last){ fill(first,la
我的包装功能有问题.
template <typename Iter,typename SomeFunction> void wrap(Iter first,Iter last,SomeFunction someFunction) { someFunction(first,last); } 我想像这样使用它: template <typename Iter> void fill5(Iter first,Iter last) { fill(first,last,5); } int main() { vector<int> v(100,-1); wrap(v.begin(),v.end(),fill5); } 但我明白了 test.cpp: In function ‘int main()’: test.cpp:16:40: error: no matching function for call to ‘wrap(std::vector<int>::iterator,std::vector<int>::iterator,<unresolved overloaded function type>)’ test.cpp:16:40: note: candidate is: wrap.h:6:6: note: template<class Iter,class SomeFunction> void wrap(Iter,Iter,someFunction) 我知道如果我会这样称呼这个功能 wrap(v.begin(),fill5< vector<int>::iterator> ); 它会编译.但我是否总是要明确这样做?太糟糕了.为什么编译器无法推断出将使用哪个函数?是否有可能编写wrap函数来获取第一个参数? 解决方法
因为fill是一个模板函数,所以基本上存在无限数量的重载,编译器不知道选择哪一个.
如果你声明你的第二个模板参数来描述一个带有2个Iter类型参数的函数,那么它就可以推导出它.以下示例有效,看起来就像您想要的那样.它并不像你的尝试那样通用.它确保被调用的函数返回void并且需要2个Iter参数. template <typename Iter > void wrap( Iter first,void(*someFunction)(Iter,Iter) ) { someFunction( first,last ); } template <typename Iter> void fill5(Iter first,5); } int main( int,char ** ) { std::vector<int> v(100,-1); wrap(v.begin(),fill5); return( 0 ); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |