template <class t>
class A{
private:
int value;
public:
template <class d>
A (const A<d> & a);
void f(A<string>);
void g(A<const char*>);
void foo{ //这个是什么意思呢?我看不明白。
A<string> a;
f(a);//ok, calls built-in default copy
constructor;(default?而不是使用那个模板的?为什么?)
g(a);//ok, calls template construtor.
首先.C++的爸爸说
如果我不用大铁锤就不要背着大铁锤到处跑.
template <class t>
class A{
private:
int value;
public:
template <class d>
A (const A<d> & a);
编译器根据给定的T值生成不同的A_*类型,
这些A_*类型一旦生成后互相在类型上来说是没有本质联系的..
.A_String和A_ConstChar类和CFoo和CBar一样,对编译器来说完全没有本质联系.
如果 只有书中的实例程序仅仅只有
1. void f(A<string>);
2. void g(A<const char*>);
这两个声明就只会导致两个不同的A_String和A_ConstChar类出现.
但是不会导致
在A_String类里面出现
/*template <class d> */
A_String (const A_ConstChar& a);
同样A_ConstChar类里面也不会定义
A_ConstChar(const A_String & a);
这样的定义.
因为编译器不会为没有用到的东西生成任何代码.(因为我不用就不要生成这些代码)
template <class d>
A (const A<d> & a);
这个模板虽然是在模板类里面定义的,但是同样也只有在明确的使用到了才会给予定义
3. A<string> a;
4. g(a);//ok, calls template construtor.
//2. void g(A<const char*>);
但是a是属于A<string>类型的
上面的这两句话仅仅导致了 在A_String类中的
template <class d>
A (const A<d> & a);得到了激活
生成了
class A_String{
private:
int value;
public:
A _String(const A_String& xxx);
//默认生成的拷贝cntor,我们看不到
A _String(const A_ConstChar& a);
//4. g(a);这句话把它整出来了,模板生成的
然而A_ConstChar的类代码却是:
class A_ConstChar{
private:
int value;
public:
A _ConstChar(const A_ConstChar& xxx);
//默认生成的拷贝cntor,我们看不到
//没有激活模板函数,因为现有使用A模板的任何代码没有使用到
f(a);//ok, calls built-in default copy constructor;
(default?而不是使用那个模板的?为什么?)
因为已经有了
A _String(const A_String& a);
//默认生成的拷贝cntor,我们看不到
存在
为什么要去调用模板生成的A _String(const A_ConstChar& a);
呢
f的定义是: 1. void f(A<string>);
---------------
而g函数的定义是:
2. void g(A<const char*>);
这样除了使用模板生成的A _String(const A_ConstChar& a);
就没的使用的了办法了.
g(a);//ok, calls template construtor.
-----------------
A_ConstChar和A_String是我杜撰的类名,实际编译器生成的可能是
A_CCdsfsdkfjk和A_StrSJHKIudsf之类的东西