C++ template problem.

Recommended Posts

VonDouchee    122
template<class DataType = int>
struct TreeNode_t
{
TreeNode_t*	left;
TreeNode_t*	right;
DataType	data;
TreeNode_t(const DataType d):data(d){};
};

//, typename NodeType = TreeNode_t<DataType>

template<class DataType = int, class NodeType = TreeNode_t<DataType> >
class BinSTree
{
protected:
typedef std::vector<NodeType*>	NodeList;
typedef NodeList::iterator NodeIterator;
public:
NodeType* root;
NodeList nodeList;	//for easy deallocating.

{
NodeType* node = root;
if(node == NULL)
{
node = new TreeNode_t(data);
nodeList.push_back(node);
}
};
};

this bit of code can't compile and the errors i'm getting are:
WaterLoo.cpp
WaterLoo.cpp(39) : warning C4346: 'std::vector<_Ax*>::iterator' : dependent name is not a type
prefix with 'typename' to indicate a type

WaterLoo.cpp(54) : see reference to class template instantiation 'BinSTree<DataType,NodeType>' being compiled

WaterLoo.cpp(39) : error C2146: syntax error : missing ';' before identifier 'NodeIterator'

WaterLoo.cpp(39) : error C2501: 'BinSTree<DataType,NodeType>::NodeIterator' : missing storage-class or type specifiers

WaterLoo - 2 error(s), 1 warning(s)

which could mean there is something wrong with the template parameter, but what is out my scope. i dont know much about templates.
Edit by Fruny: Tweaked error messages for readability, source formatting.

Share on other sites
Fruny    1658
Did you know: You can search your compiler documentation for the signification of errors and warnings.

Quote:
 WaterLoo.cpp(39) : warning C4346: 'std::vector<_Ax*>::iterator' : dependent name is not a type prefix with 'typename' to indicate a type

This line told you exactly what was wrong and what you needed to do to fix it.

NodeList is a class template std::vector<NodeType*>
NodeType is a template parameter of your class.

Therefore NodeList::iterator is a dependent name.
That means that the actual nature of NodeList::iterator depends on NodeType. For some specializations of std::vector, it might be a static member variable, for others, it might be a typedef. (Ok, for vector, in fact, it is always a typedef)

By default, C++ assumes that something of the form NodeList::iterator refers to a static member variable: with dependent names, it cannot guess!

To indicate that it really refers to a type, you need to use the typename keyword.

typedef typename NodeList::iterator NodeIterator;

That should fix the other errors, too.

Share on other sites
VonDouchee    122
i did search for the errors but it didn't tell me much except for some examples. i didn't know the waring is the thing that screwed it up...