为什么我的函数调用与此泛型函数实现不匹配?
Why doesn't my function call match this generic functions implementation?
看起来编译器非常接近做我想做的事(因为它调用了我的函数作为候选函数),但我不知道我做错了什么。
#include <stdio.h>
#include <stdlib.h>
#include <list>
using namespace std;
template <class U, template<class U> class T>
void AppendSorted( T<U>& l, U val )
{
typename T<U>::reverse_iterator rt = l.rbegin();
while( ((*rt) > val) && (rt != l.rend()) )
rt++;
l.insert( rt.base(), val );
}
int main( int argc, char* argv[] )
{
list<int> foo;
AppendSorted<int, list<int> >( foo, 5 );
list<int>::iterator i;
for( i = foo.begin(); i != foo.end(); i++ )
{
printf("%dn",*i);
}
return 0;
}
我得到的错误是:
test.cpp: In function ‘int main(int, char**)’:
test.cpp:21:43: error: no matching function for call to ‘AppendSorted(std::list<int>&, int)’
test.cpp:21:43: note: candidate is:
test.cpp:8:6: note: template<class U, template<class U> class T> void AppendSorted(T<U>&, U)
此签名
template <class U, template<class U> class T>
void AppendSorted( T<U>& l, U val )
表示将有一个具体类型 ( class U
) 和一个模板 ( template<class U> class T
)。
此调用
AppendSorted<int, list<int> >( foo, 5 );
提供两种具体类型,int
和list<int>
。 list
是模板,list<int>
是具体类型、模板实例,但不是模板。
只需更改函数以接受集合的具体类型:
template <class U, class T>
void AppendSorted( T& l, U val )
{
typename T::reverse_iterator /* or auto */ rt = l.rbegin();
while( (rt != l.rend()) && ((*rt) > val) )
rt++;
l.insert( rt.base(), val );
}
并让编译器推断类型参数,而不是指定它们。
AppendSorted( foo, 5 );
std::list
是模板采用两个参数 - 而不仅仅是一个。还有第二个默认参数。
您需要这样的模板函数来匹配列表:
template <class U, template<class U,class A> class T>
void AppendSorted( T<U,std::allocator<T>>& l, U val );
但是std::set
呢 - 它需要 3 个参数?
我不确定 - 也许可变参数模板会有所帮助......
但试试这个:
template <class U, class Container>
void AppendSorted( Container& l, U val);
>std::list
实际上有两个模板参数:
#include <stdio.h>
#include <stdlib.h>
#include <list>
using namespace std;
template <class U, template<class> class AL, template<class,class> class T>
void AppendSorted( T<U,AL<U>>& l, U val ) {
typename T<U,AL<U>>::reverse_iterator rt = l.rbegin();
while( ((*rt) > val) && (rt != l.rend()) )
rt++;
l.insert( rt.base(), val );
}
int main( int argc, char* argv[] ) {
list<int> foo;
AppendSorted( foo, 5 );
list<int>::iterator i;
for( i = foo.begin(); i != foo.end(); i++ ) {
printf("%dn",*i);
}
return 0;
}
现在它将编译,但你的代码中有逻辑错误 - 你有过去的迭代器。 要解决此问题,请在循环中,首先检查rend()
:
while(rt != l.rend() && *rt > val)
相关文章:
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 分段 排序函数实现中的错误
- 无法去函数实现 vim
- C++ 20 中的运算符 == 和 <=> 应该作为成员还是自由函数实现?
- 为什么在这种情况下不调用我的虚拟函数实现?
- 我能否通过将函数实现为类对象方法来避免使用互斥锁
- 嵌套的模板结构构造函数实现
- C++接口的工厂函数实现
- 链表中的递归长度函数实现
- 我可以期望某些 STL 函数实现是可自动矢量化的吗?
- 如何将深拷贝构造函数实现到链表中?
- 虚拟 CTOR 的克隆函数实现是否有问题
- 没有捕获列表的 lambda 通常作为普通函数实现吗?
- C++二叉树打印函数实现
- C++:默认构造函数实现
- C++派生类中的纯虚函数实现
- 决定放置函数实现的位置
- 强制实施纯虚函数实现,可能使用不同的参数类型
- 如何让成员函数实现依赖于类的模板参数?
- 我们如何将Ostream函数作为类的成员函数实现,而不是作为朋友函数,以便我可以用作虚拟函数