Specialize a class template within a class template?
The definition below is failing... I'm thinking it has something to do with specializing a class template (Vector) within another class template (Graph). Thanks!
this is the part giving me trouble (defined in Graph below) ->
std::map<KeyType, Vertex<KeyType, ObjectType> > vertexes;
template <class KeyType, class ObjectType>
class Vertex
{
private:
KeyType key;
const ObjectType* object;
public:
Vertex(const KeyType& key, const ObjectType& object);
const KeyType getKey();
};
template <class KeyType, class ObjectType>
class Graph
{
private:
std::map<KeyType, Vertex<KeyType, Object开发者_开发问答Type> > vertexes;
public:
const Vertex<KeyType, ObjectType>& createVertex(const KeyType& key, const ObjectType& object);
};
template <class KeyType, class ObjectType>
const Vertex<KeyType, ObjectType>& Graph<KeyType, ObjectType>::createVertex(const KeyType& key, const ObjectType& object)
{
Vertex<KeyType, ObjectType> *vertex = new Vertex<KeyType, ObjectType>(key, object);
vertexes.insert(pair<KeyType, Vertex<KeyType, ObjectType> >(vertex.getKey(), vertex));
return *vertex;
};
Visual Studio 10 reports:
Error 1 error C2228: left of '.getKey' must have class/struct/union c:\documents\visual studio 2010\projects\socialnetwork\socialnetwork\graph.h 46 1 SocialNetwork
The line mentioned in the error corresponds to the the vertexes.insert call near the end.
UPDATE: made correction as suggested by 2 posters of changing the >> to > >. No difference. Error persists.
Your vertex
is a pointer. To access getKey
you need to use ->
operator, not .
. Plus, you can use std::make_pair
to avoid repeating the types.
vertexes.insert(std::make_pair(vertex->getKey(), *vertex));
Not having the error message itself, I can't be that helpful. But if I may venture a guess:
Unless you are using C++0x,
std::map<KeyType, Vector<KeyType, ObjectType>> vertexes;
will fail parsing, since >>
at the end is parsed as the operator, as opposed to the end of a nested template parameter list. So, you'll need to change that to
std::map<KeyType, Vector<KeyType, ObjectType> > vertexes;
This does get fixed in C++0x, though.
First change from Vector to Vertex (typo?). The second error is the "<<", if you put them together it will be the shift operator. Here is how that line should be:
std::map<KeyType, Vertex<KeyType, ObjectType> > vertexes;
Edit: With the new information I could spot another error:
In the method createVertex you are creating a new Vertex but using it as Value. For example, in this line:
vertexes.insert(std::pair<KeyType, Vertex<KeyType, ObjectType> >(vertex.getKey(), vertex));
The call:
vertex.getKey()
Vertex is a pointer, so you should change to vertex->getKey(). There are more errors, but all related to the fact that vertex is a pointer being treated as a value.
精彩评论