1

コンパイラーは(候補としての関数を呼び出すため)私が望むことを実行するのに非常に近いようですが、私は何が間違っているのかわかりません。

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

3 に答える 3

2

この署名

template <class U, template<class U> class T>
void AppendSorted( T<U>& l, U val )

1つの具象型(class U)と1つのテンプレート(template<class U> class T)があることを示します。

この呼び出し

AppendSorted<int, list<int> >( foo, 5 );

2つの具体的なタイプを提供し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 );
于 2012-10-15T21:21:47.183 に答える
2

std::listテンプレートは、1つだけでなく2つのパラメータを取ります。2番目のデフォルトパラメータがあります。

リストに一致させるには、このようなテンプレート関数が必要です。

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);
于 2012-10-15T21:38:28.850 に答える
1

std::list実際には2つのテンプレートパラメータがあります。

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

        return 0; 
}

これでコンパイルされますが、コードに論理エラーがあります-終了後のイテレータがあります。これを修正するには、whileループで、rend()最初に次のことを確認します。

    while(rt != l.rend()  &&  *rt > val)
于 2012-10-15T21:42:39.090 に答える