http://bbs.csdn.net/topics/190144045 1 #include<iostream>
2 #include<vector>
3 #include<string>
4
5
6 using namespace std;
7
8 template <typename T,size_t size>
9 class fixed_vector
10 {
11 public:
12 typedef T* iterator;
13 typedef const T* const_iterator;
14 fixed_vector()
15 {
16 cout<<"默认构造函数"<<endl;
17 }
18
19
20 template<typename T2,size_t osize> //如果模板函数的T和类的T可能不是一个类型的话,那么两个T要命名成不同的名字 (否则在linux下编译不成功. 在vs2010下可以同名)
21 fixed_vector( const fixed_vector<T2,osize>& other)
22 {
23 cout<<"模板拷贝构造函数1"<<endl;
24 }
25
26 fixed_vector( const fixed_vector& other)
27 {
28 cout<<"模板拷贝构造函数2"<<endl;
29 }
30
31 template <typename T2,size_t osize>
32 fixed_vector<T2,size>& operator=(const fixed_vector<T2,osize>& other) //注意这里返回的是size而不是osize
33 {
34 cout<<"模板赋值函数1"<<endl;//这不是真的赋值函数
35 return *this;
36 }
37
38 fixed_vector<T,size>& operator=(const fixed_vector& other) //注意这里返回的是size而不是osize
39 {
40 cout<<"模板赋值函数2"<<endl;//这不是真的赋值函数
41 return *this;
42 }
43
44 iterator begin()
45 {
46 return m_v;
47 }
48 iterator end()
49 {
50 return m_v+size;
51 }
52
53 const_iterator begin() const
54 {
55 return m_v;
56 }
57
58 const_iterator end() const
59 {
60 return m_v+size;
61 }
62
63 private:
64 T m_v[size];
65 };
66
67
68 int main()
69 {
70 cout<<"--------begin <char, 4>----------"<<endl;
71 fixed_vector<char,4> fv_char;
72 cout<<"--------begin <int , 4>----------"<<endl;
73 fixed_vector<int,4> fc_int1;
74 cout<<"--------begin <int, 8>(<int , 4>)----------"<<endl;
75 fixed_vector<int,8> fc_int2(fc_int1);//这里将调用模板拷贝构造函数
76 cout<<"--------begin <int, 8> = <int , 4>----------"<<endl;
77 fc_int2=fc_int1;//这里将调用模板赋值函数
78
79 cout<<"--------begin <int , 4>----------"<<endl;
80 fixed_vector<int,4> fc_int3;
81 cout<<"--------begin <int, 4>(<int , 4>)----------"<<endl;
82 fixed_vector<int,4> fc_int4(fc_int3);//这里不会调用模板拷贝构造函数
83 cout<<"--------begin <int, 4> = <int , 4>----------"<<endl;
84 fc_int3=fc_int4;//不调用模板赋值函数
85
86 //system("pause");
87 return 0;
88 }
http://blog.chinaunix.net/uid-7448695-id-2626460.html
昨天看《Exceptional C++》,发现一个从来没有注意到标准(C++ 标准 12.8/2,note 4):“模板构造函数永远都不能成为拷贝构造函数”。所以模板构造函数永远不能取代拷贝构造函数,即便有了模板构造函数,默认拷贝构造函数还是会合成的。
例如:
`class A { public: // 这个构造函数不会掩盖默认拷贝构造函数 template A (const T& t) {} };` |
同样的情况对于 operator=() 一样适合。也就是模板赋值函数不会覆盖默认拷贝赋值函数。
[美] Sutter, Hurb 著;聂雪军 译。《Exceptional C++ 中文版》。北京:机械工业出版社,2007 年 1 月第 1 版。第 11 页。
原文链接: https://www.cnblogs.com/silentNight/p/5545643.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/234293
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!