template class template member functions (member function template) implicit processing (implicit) changes
This address: http://blog.csdn.net/caroline_wendy/article/details/24233693
pointers Support implicit conversions (implicit conversion), where derived class pointers can be converted to base-class pointers in dynamic bindings.
However, the instantiation of the template (instantiations) is a separate existence,
The instantiated template (smartptr<derived>) of a derived class cannot be converted to a template instantiated by the base class (smartptr<base>);
Writing that needs to be understood , because derived classes can also continue to be a base class, producing derived classes, so the constructor cannot be written directly .
Use member function templates (Memberfunction template), and then declare a template parameter to provide such an implicit conversion.
In order to use transformations that can only occur in pointers that can be converted, such as "derived->base", cannot be reversed, so the introduction of the relevant constraint inference can be enough to convert.
Call the get () function in the Member initialization list (member initialization list) to infer whether the implicit conversion is sufficient.
A constructor that uses a member function template is one of the member functions, not an overloaded copy constructor, so the class proactively generates a default constructor .
Code Note: The first one can be converted, the second cannot be converted, and the third uses the default constructor.
Code:
/* * test.cpp * * Created on:2014.04.20 * author:spike *//*eclipse CDT, gcc 4.8.1*/#include <iostream>usin G namespace Std;class Base{};class derived:public Base {};template<typename t>class smartptr {public:SmartPtr () = Default;template<typename u>smartptr (const smartptr<u>& Other): Heldptr (Other.get ()) {Std::cout < < "Smartptr:copyconstructor" << Std::endl;} t* get () const {return heldptr;} Private:t* heldptr;}; int main () {smartptr<derived> SPD; Smartptr<base> SPB (SPD);//smartptr<base> spb1;//smartptr<derived> SPD1 (SPB1); Unable to perform stealth conversion smartptr<base> SPD2; Smartptr<base> spd21 (SPD2); Use the default copy constructor for return 0;}
Output:
Smartptr:copyconstructor
Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.
C + +-template class template member functions (member function template) implicit processing (implicit) changes