Reputation: 45
I have 2 classes, A and B and B is derived from A. I'm not allowed to change them. I'm implementing smart pointer class.
template <typename T>
class SmartPtr{
...
SmartPtr& operator=(const SmartPtr& p);
...
}
template<typename T>
SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr & p) {
++*p.cnt;
if(--*cnt == 0) {
delete ptr;
delete cnt;
}
ptr = p.ptr;
cnt = p.cnt;
return *this;
}
I get error when I try to assign SmartPtr A to SmartPtr B as operand types are different. How can I fix that without changing A and B?
Upvotes: 0
Views: 125
Reputation: 13430
I think you might mean SmartPtr<A>
and SmartPtr<B>
. Of course you won't be able to assign them, because class A is not class B.
You will need to add another assignment operator, that looks like this
tempalte <typename U>
SmartPtr<T>& operator=(const SmartPtr<U>& p);
if you like to, you could use std::enable_if
to make sure, U is derived from T
template <typename U>
SmartPtr<T>& operator=(const typename SmartPtr<std::enable_if<std::is_base_of<T, U>::value, U>::type &p);
and then you can implement this, by using dynamic_cast
in your code to convert A to B
using std::shared_ptr you could use this http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast
Upvotes: 1