c++ - 为什么我的函数调用不匹配这个通用函数实现?

标签 c++ templates

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

#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("%d\n",*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 );

关于c++ - 为什么我的函数调用不匹配这个通用函数实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12904039/

相关文章:

c++ - 使用 OpenSSL 的 SCTP 上的 DTLS

c++ - shgetvalue 运行时错误

c++ - 性能:C++ 中的指针取消引用

C++矩阵类模板

java - 在运行时通过变量设置 T 模板类型

c++ - 使用模板是否节省内存

c++ - 模板 + Typedef C++

C++ 部分模板特化 : Member Functions

css - Aweber 电子邮件模板,在 outlook 中宽度乱七八糟

C++ 兄弟模板类作为模板模板参数