一 成员模板
1. class 的成员可以是template。
2. 但成员模板不能是virtual。
3. 该语言特性往往被用来支持class template内的成员之间的自动类型转换。
template <typename T>
class A {
public:
template <typename U>
void assign(const D<U>& u)
{
v = u.getvalue();
}
T getvalue()
{
return v;
}
private:
T v;
}
二 模板构造函数
1. 成员模板的一个特殊形式是模板构造函数。
2. 被提供用于“对象被复制时给予隐式类型转换”的能力。
3. template构造函数并不压制copy构造函数的隐式声明。如果类型完全吻合,隐式的copy函数会被生成出来, 并被调用。
#include <iostream>
template <typename T>
class A
{
public:
template <typename U>
A(const U& a) {
std::cout << "template constructor" << std::endl;
}
A() {
std::cout << "default constructor" << std::endl;
}
};
int main() {
A<int> i; // default constructor
A<int> ii(i); // implicitly generated copy constructor
A<double> d(i); // template constructor
std::cin.get();
return 0;
}
三 参考
《C++ 标准库》