我遇到以下课程的问题。我得到错误" Tree.cpp:12:56:错误:模板参数列表中参数2的类型/值不匹配'template class std :: multiset'// Tree.cpp:12:56:注意:预期一个类型,得到'(Tree :: compare<)'"。我不明白我应该如何在multiset声明中传递比较器类型。你能帮帮我吗?
#include <set>
#include <deque>
#include <iostream>
using namespace std;
template <typename T>
class Tree
{
typedef typename std::multiset<Tree<T>*, typename Tree<T>::compare > NodeSet;
private:
NodeSet children;
T content;
public:
struct compare
{
bool operator()( const Tree*& t1, const Tree*& t2 ) const
{
cout << "Comparing " << t1->GetContent() << " vs " << t2->GetContent() << endl;
return t1->GetContent() < t2->GetContent();
}
};
Tree& AppendNode( const T& node )
{
Tree* t = new Tree( node );
AttachTree( t );
return *t;
}
void Clear()
{
typename NodeSet::iterator it = children.begin();
while( children.size() != 0 && children.end() != it )
{
children.erase( *it );
delete *it;
it++;
}
}
Tree( const T& root )
{
content = root;
}
void AttachTree( Tree* t )
{
children.insert( t );
}
void Visit( std::deque<T>& exp ) const
{
exp.push_back( content );
typename NodeSet::iterator it = children.begin();
while( it != children.end() )
{
( *it )->Visit( exp ); it++;
}
}
Tree()
{}
Tree( Tree& c )
{
c.DeepCopyTo( this );
}
T& operator =( const Tree& b )
{
b.DeepCopyTo( this );
}
~Tree()
{
cout << "in destructor for" << this << endl;
Clear();
}
void DeepCopyTo( Tree* dest ) const
{
dest->content = content;
typename NodeSet::iterator it = children.begin();
while( it != children.end() )
{
Tree* t = new Tree();
( *it )->DeepCopyTo( t );
dest->AttachTree( t );
it++;
}
}
void Print()
{
typename NodeSet::iterator it = children.begin();
while( it != children.end() )
{
cout << *it << ",";
it++;
}
}
};
int main()
{
Tree<int> tree( 8 );
tree.AppendNode( 5 );
}
答案 0 :(得分:1)
您可能希望将此行更改为
typedef
typename std::multiset<Tree*, typename Tree::compare >
NodeSet;
请注意,compare
是dependent name,因此您需要使用typename
。
此外,您应该考虑将结构compare
移到此行上方,因为此行引用它。
还有两件事要注意。
您可能希望将compare
更改为
struct compare {
bool operator()(const Tree* t1, const Tree* t2) const {
cout << "Comparing " <<t1->GetContent() <<" vs "<<t2->GetContent()<<endl;
return t1->GetContent() < t2->GetContent();
}
};
不幸的是,GetContent
似乎无法在代码中的任何位置定义。