polymorphism

Tiago Candeias tcandeia@ualg.pt
Wed Jun 4 13:32:00 GMT 2003


Hi Eljay,

I have read that article.
And I tried to use the author's code, but I have some problems in
implementing the operator>> in the poly<T> struct.
So, due to that reason and because this was pointed out in 2000, I asked
if the gcc have already that struct to call.

So my problem now, is only to implement the operator>>, this is
low-level and it is difficult for me.

#ifndef __POLY_H__
#define __POLY_H__

template <typename T>
struct poly_base {
	virtual ~poly_base() {}         // support derivation
	virtual poly_base* clone() = 0; // copy derived object
	virtual T& get_object() = 0;    // stored in derived
};
  
template <typename T, typename S>
struct poly_object: public poly_base<T> {
	poly_object(S const& s): object(s) {}
	poly_base<T>* clone() { return new poly_object(*this); }
	T& get_object() { return object; }
private:
	S object;
};
    
template <typename T>
struct poly {
	poly(): ptr(0) {}                 // no object by default
  
	template <typename S>             // creation from prototype
	poly(S const& s):
		ptr(new poly_object<T, S>(s)) {}
 
	poly(poly const& p):              // create a cloned object
		ptr(p.ptr->clone()) {}
  
	~poly() { delete ptr; }           // release current object
   
	poly& operator= (poly const& p) { // assign cloned object
		poly_base<T>* tmp = p.ptr->clone();
		std::swap(ptr, tmp);
		delete tmp;
		return *this;
	}
   
	// Accessors to the hold object:
	T& operator*() const { return ptr->get_object(); }
	T* operator->() const { return &(ptr->get_object()); }
private:
	poly_base<T>* ptr;
};
   
template <typename T>
bool operator< (poly<T> const& p1, poly<T> const& p2) {
	return *p1 < *p2;
}

template <typename T, typename cT, typename traits>
std::basic_ostream<cT, traits>&
	operator<< (std::basic_ostream<cT, traits>& out,poly<T> const& p) {
    	return out << *p;
}

// hacking this rotine
template <typename T, typename cT, typename traits>
std::basic_istream<cT, traits>&
	operator>> (std::basic_istream<cT, traits>& in,poly<T> &p) {
		T obj = p.get_object();
    	return (in >> obj);
}

#endif


Any suggestion?

Tiago

> Hi Tiago,
> 
>  >This is a polymorphic problem as described in (STL and OO Don't Easily 
> Mix) http://www.oonumerics.org/tmpw00/kuehl.html in 2000.
> 
> The solution to your problem is also described in the (STL and OO Don't 
> Easily Mix) http://www.oonumerics.org/tmpw00/kuehl.html article.
> 
> I refer you to the articles conclusion, "Although STL algorithms and 
> containers don't seem to mix at all with polymorphic objects, it is 
> actually not that bad. "
> 
> --Eljay
> 
> 
> 




More information about the Gcc-help mailing list