为什么我的函数调用与此泛型函数实现不匹配?

Why doesn't my function call match this generic functions implementation?

本文关键字:函数 实现 不匹配 泛型 我的 函数调用 为什么      更新时间:2023-10-16

看起来编译器非常接近做我想做的事(因为它调用了我的函数作为候选函数),但我不知道我做错了什么。

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

提供两种具体类型,intlist<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)