• Advertisement
Sign in to follow this  

static member in template class problem

This topic is 4763 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi, i have a simple object factory, which compiles fine under VS6 but wont with VS7 heres the code: template< class O, class P, class I > class Maker { public: virtual ~Maker() {} //selects maker static O* newObject(I id, P p) { Maker* m = (*registry.find(id)).second; if( m == 0) return 0; return m->makeObject(p); } protected: //registers type Maker(I classId) { registry[classId] = this; } //instantiates object from parameters virtual O* makeObject(P) {return 0;}; private: typedef Maker<O, P, I>* MakerPtr; typedef std::map<I, MakerPtr> MakerMap; static MakerMap registry; }; this is in a cpp std::map<I, Maker<O, P, I> *, std::less, std::allocator< Maker<O, P, I> *> > Maker<O, P, I>::registry the compiler is saying that registry is allready defined. i do not have any other instances of registry (when i comment this line out i get a linker error) is there something that .NET is catching that VS6 doesnt? any help would be appreciated,

Share this post


Link to post
Share on other sites
Advertisement
You shouldn't be getting multiple defines, you should be getting registry as being undefined. This is because your static member initialization for the template should be in a header, not in a cpp file -- when in a cpp, you can only use the static from the translation unit in which it is defined.

You should have:


template< class O, class P, class I >
std::map<I, Maker<O, P, I> *, std::less<I>, std::allocator< Maker<O, P, I> *> > Maker<O, P, I>::registry;


in a header (most-likely the same header that has the class template definition)

Share this post


Link to post
Share on other sites
Offtopic:

How bizarre. We're both working on almost the exact same source code at the same time. Did you port yours from http://www.adtmag.com/joop/crarticle.asp?ID=1520 by any chance?

Share this post


Link to post
Share on other sites
This is what I have:

template <class Object> typename Maker <Object>::MakerMap Maker<Object>::s_registry;

You can put it in the header file if you want. Change "class Object" to "class O, class P, class I", and "Object" to "O, P, I" and it'll work. There's no need for the std::less (it's the default argument anyway) and std::allocater stuff.

Share this post


Link to post
Share on other sites
thanks, all i need to do was get rid of the std:less part for it to work
but it seemed to force me to use it in vs6,

thanks again.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement