Archived

This topic is now archived and is closed to further replies.

Nekhmet

Tricky C++ template problem.

Recommended Posts

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]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
eh? conversion?

your making the smart point wrapper do converisons?

That''s not general purpose, why use templates at all?

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites