Pointers support implicit conversions (implicit conversion), in which derived class pointers can be converted to base class pointers.
But the instantiation of the template (instantiations) is separate,
The instantiated template (smartptr<derived>) of the derived class cannot be converted to a template (smartptr<base>) that is instantiated by the base class;
Need to be written explicitly, because derived classes can also continue to be base classes, generating derived classes, so you cannot write constructors directly.
You can provide this implicit conversion by using the member function template, template, and declaring a template parameter.
In order to use a transformation only occurs in a pointer that can be converted, such as "Derived->base", which cannot be inverted, so the relevant constraint is introduced to determine whether it can be converted.
Call the Get () function in the member initialization list (initialization) to determine whether an implicit conversion is possible.
The constructor of the member function template, which is one of the member functions, is not an overloaded copy constructor, so the class automatically 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>
using 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 return
0;
Output:
Smartptr:copyconstructor
Author: csdn Blog spike_king
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/