Tricky C++ template problem.

Started by
4 comments, last by Nekhmet 20 years ago
I'm experimenting with smart pointers, and I'm having a problem. The compiler won't accept this code: template <class Type> class ptr { public: ptr(ptr<Type> &p) ... ptr(ptr<object> &p) ... }; The one constructor is supposed to be a copy-constructor, the other is for conversion. The problem is that the compiler sees the possibility that Type == object, in which case the two methods have the same signature. Is there any way to make this work? [edited by - Nekhmet on April 4, 2004 7:43:44 PM]
Advertisement
eh? conversion?

your making the smart point wrapper do converisons?

That''s not general purpose, why use templates at all?
The following works for me:
template<class Type>class ptr{public:	ptr() {}	ptr(ptr<Type>& p) {}	template<class Other>	ptr(const ptr<Other>& o) {}};	ptr<double> p1;	ptr<int> p2(p1);        ptr<int> p3(p2);


you templatized your conversion ctr, right?

edit: fixed code x2


[edited by - sjelkjd on April 4, 2004 10:01:44 PM]
The conversion is intended for downcast.

The idea is, you have a class heirarchy like this:

object
- vector
- hashtable


you also have related pointer types:

ptr<object>
ptr<vector>
ptr<hashtable>

and you should be able to do a downcast:

ptr<object> o = new vector(10); // A static upcast
ptr<vector> v = o; // Does a dynamic_cast internally.



[edited by - Nekhmet on April 4, 2004 7:59:35 PM]
take a look on gamedev or google for the Loki or the boost library for a look at smart pointer code.
Nekhmet - see my edited code above. If you templatize your conversion constructor, the code you have should work. The reason is that the template resolution process will always choose the most specific function if it has a choice, and will produce an error if several functions are equally specific(through conversions, for instance).

This topic is closed to new replies.

Advertisement