Templates and derived classes

I'm having problems using derived classes in templates.

I have a template smart pointer class:

1
2
3
4
5
6
7
template <class type> 
class RefPointer
{
public:
	RefPointer<type>& operator= (const RefPointer<type>& rkReference)
	//other stuff
};


And a class that contains a map of smart pointers to a base class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ContainerClass
{
public:
	map<string, RefPointer<Base> > BaseMap;

	createDerived(const string& name)
	{
		RefPointer<Derived> p_derived = new Derived();

		BaseMap[name] = p_derived;

		return p_derived;
	}
	// other stuff
};


When I try to pass RefPointer<Derived> to something that takes RefPointer<Base>, I get the following error:

1
2
error C2679: binary '=' : no operator found which takes a right-hand 
operand of type 'RefPointer<type>' (or there is no acceptable conversion)


If I change the map to take RefPointer<Derived> I get no errors, so the problem is that a template of a derived class is not considered inherited from a template of a base class. I've tried casting with

BaseMap[name] = (RefPointer<Base>)p_derived;

but then get the following error:

error C2440: 'type cast' : cannot convert from 'RefPointer<type>' to 'RefPointer<type>'

Is there any way around this?
Last edited on
Your smart pointer class needs to have implicit upcasting:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<typename T>
class RefPointer
{
private:
  T* ptr;
  //...etc

public:

  template <typename U>
  RefPointer(const RefPointer<U>& p)
  {
     ptr = p.ptr;
     // etc
  }



Or of course you could use a smart pointer class that already has all this functionality, like boost::shared_ptr
Thanks a lot for the quick reply, that's exactly what I needed. Not only is the problem solved, but I now know what to search for to find out more about this.

And I'm working on this to get better at programming, which is why I opted to implement my own class rather than using (a better) one that is already implemented :D
Topic archived. No new replies allowed.