A special form of a member template is a template constructor. Template constructors are usually
provided to enable implicit type conversions when objects are copied. Note that a template
constructor does not hide the implicit copy constructor. If the type matches exactly, the implicit
copy constructor is generated and called. For example:
template <class T>
class MyClass<T> {
public:
//copy constructor with implicit type conversion
//- does not hide implicit copy constructor
template <class U>
MyClass(const MyClass<U>& x);
};
void f()
{
MyClass<double> xd;
MyClass<double> xd2(xd); // calls built-in copy constructor
MyClass<int> xi (xd); // calls template constructor
}
Here, the type of xd2 is the same as the type of xd, so it is initialized via the built-in copy
constructor. The type of xi differs from the type of xd, so it is initialized by using the template
constructor. Thus, if you write a template constructor, don't forget to provide a copy constructor, if
the default copy constructor does not fit your needs. See Section 4.1, for another example of
member templates.
posted on 2009-06-01 16:21
noyear 阅读(48)
评论(0) 编辑 收藏 引用