real pointers support implicit conversions very well. (eg. derived->base, non const -> const)
iterators into stl containers are almost always smart pointers
class top
class middle : public top
class bottom : public middle
now in templates to ge tmiddle to convert to top we need
template <typename t?
class smartptr {
public:
explicit smartptr(t* realptr);
};
smartptr<top> pt1 = smarptr<middle>(new middle); to get this to compile we will need the corresponding constructor in the smartptr definition, since compilers dont assume any relation between smartpttr<top> and smartptr<middle> classes.
easiest way to get around is ( but bad)
template typename<t>
class smartptr{
public:
template <typename u>
smartptr(const smartptr<U> & other);,....
}
but this allows converting top object to middle object also.
such functions are called generalized copy constructors. its not declared explicit sive type conversions among built in pointer types.
so what we do is simply use member initialization list to initialize parameters with true ptrs of the other object . then it can compile only if each naked ptr can be converted to the type to which we are trying to convert the object.
there are more things here that i dont really understand ...
c+= states that if a copy constructor is needed and you dont declare one it will be generated for you ( so if you only have a generalized template than it wont be used by the compiler )
things to remember:
use member function templates to generate functions that accept al lcompatible types
if you declare member templates for generalized copy construction or generalized assignemnt you will still need to declare normal copy constructor and copy assignment operator also.
No comments:
Post a Comment