c++ - template inherited class derived-base assignment -


i have 2 classes, , b , b derived a. i'm not allowed 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 error when try assign smartptr smartptr b operand types different. how can fix without changing , b?

your answer

i think might mean smartptr<a> , smartptr<b>. of course won't able assign them, because class not class b. need add assignment operator, looks this

tempalte <typename u> smartptr<t>& operator=(const smartptr<u>& p); 

if to, use std::enable_if make sure, u derived t

template <typename u> smartptr<t>& operator=(const typename smartptr<std::enable_if<std::is_base_of<t, u>::value, u>::type &p); 

and can implement this, using dynamic_cast in code convert b

the 'correct' answer

using std::shared_ptr use http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -