Board index » cppbuilder » Need help with friends of class templates
Vivi Orunitia
![]() CBuilder Developer |
Need help with friends of class templates2004-01-22 01:14:31 PM cppbuilder108 Hi all, I wrote a smart pointer class that uses reference counting for my own learning purposes but I'm running into a bit of trouble overloading operator << as a friend. This is what the source looks like: mysmart_ptr.h: #ifndef _MYSMART_PTR_H #define _MYSMART_PTR_H #include <iostream> #include <map> template <typename T> class mysmart_ptr { public: mysmart_ptr(); mysmart_ptr(T* const ptr); mysmart_ptr(const mysmart_ptr &rhs); ~mysmart_ptr(); //mysmart_ptr deferencing operators T& operator *(); const T& operator *() const; T* operator ->(); const T* operator ->() const; operator bool() const; operator T*() const; bool operator ==(const mysmart_ptr &rhs) const; bool operator !=(const mysmart_ptr &rhs) const; const mysmart_ptr& operator =(const mysmart_ptr &rhs); friend std::ostream& operator <<(std::ostream &os, const mysmart_ptr &rhs); static unsigned short ctor; static unsigned short dtor; private: static std::map<T *, unsigned short>m_refcount; T *m_ptr; };//mysmart_ptr #include "mysmart_ptr.cpp" #endif mysmart_ptr.cpp: #include "mysmart_ptr.h" //all the other member functions & initalization goes here template <typename T> std::ostream& operator <<(std::ostream &os, const mysmart_ptr<T>&rhs) { os << rhs.m_ptr; return os; }//operator << Everything compiles but the linker complains: Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland Error: Unresolved external 'operator>&, const mysmart_ptr&)' referenced from E:\BORLAND\MYWORKSPACE\BIN\TEST2.OBJ Error: Unresolved external 'operator>&, const mysmart_ptr&)' referenced from E:\BORLAND\MYWORKSPACE\BIN\TEST2.OBJ From the error I'm thinking some how the compiler isn't creating any corresponding functions from my templated operator <<. Any idea what the problem is here and why it doesn't work? However, so far I have been about to find two workarounds for this. One is to overload << twice. Once as a member function and a second time as a non-member taking a stream and mysmart_ptr as parameter. When the non- member operator << gets invoked it just passes control into the member operator << in the correct format etc. The second workaround was to define friend operator << right inside my template class definition. Thought both are workable, neither are really satisfactory. Especially with the second workaround, if I have to put more friend functions into this template class things can get really yucky. So any suggestions and comments about this problem I'm having? Thanks |