On Feb 12, 1:37 pm, kmakaro...@gmail.com wrote:
> Hello, I have the following classes:
> class ServiceBase
> {
> public:
> ServiceBase() {}
> ~ServiceBase() {}
> void Stop() {}
> };
>
> class ServiceDerivate
ublic ServiceBase
> {
> public:
> ServiceDerivate() {}
> ~ServiceDerivate() {}
> };
> And I have linked smart pointer class which, does not destroy,
> but calls Stop method on its destruction:
> template <class X> class ServicePtr
> {
[...]
> };
> Since ServiceBase and ServiceDerivated have to be dynamic
> castable i wish I could use a pool of ServiceBase classes, and
> upon request to spawn new ServicePtr holding dynamic_cast to
> ServiceBase.
I'm not sure I understand. In your example, there are no
virtual functions, so the classes aren't polymorphic. I
presume, however, that this is just an oversight in the example.
And of course, you don't need dynamic_cast to convert from
ServiceDerivate to ServiceBase; that's an implicit conversion.
> Sipmle example:
> int main()
> {
> ServicePtr<ServiceBase> sbase;
> ServicePtr<ServiceDerivate> sderivate;
> sderivate=sbase;
> return 0;
> }
> which, produces:
> "no matching function for call to
> 'ServicePtr<ServiceDerivate>:
perator=(ServicePtr <ServiceBase>&)'
> note: candidates are: ServicePtr<X>& ServicePtr<X>:
perator=(const
> ServicePtr<X>&) [with X = ServiceDerivate]
It also doesn't make sense unless sbase actually points to a
ServiceDerivate. If you want to support this, with dynamic
checking, you can add something like the following to your
ServicePtr:
template< typename T >
ServicePtr& operator=( ServicePtr< T > const& other )
{
X* tmp = dynamic_cast< X* >( other.get() ) ;
// rest of processing, however...
}
In this case, I'd probably derive ServicePtr from a non-template
ServicePtrBase which contained and handled the links.
Otherwise, you'll have to make all instances of the template
friends of the other instances. (As it stands,
ServicePtr< ServiceBase > cannot access any of the members of a
ServicePtr< ServiceDerivate >.)
> Can anybody help with this. Probably I am missing something.
> I tryied to overload:
> ServicePtr& operator=(const ServicePtr<ServiceBase>& r)
> but I did not compiled either.
What was the error message? And what did the code look like?
As mentionned above, you're likely to have problems with
accessing private data members; each instantiation of the
template is a separate, unrelated class. Moving the list
handling down to a common, non-template base class should solve
that. (It also has the advantage that you can get it out of the
header files, reducing their size.)
--
James Kanze (GABI Software) email:
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34