-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector_elem_aliases.cpp
80 lines (77 loc) · 1.57 KB
/
vector_elem_aliases.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Answer to https://www.zhihu.com/question/54157667
*/
#include <iostream>
using namespace std;
//基类base_vector
template <class T, int N>
struct base_vector{
static_assert(N>1, "Dimension should be positive!\n");
char a[N];
};
template <class T>
struct base_vector<T,2>{
union{
struct{T x,y;};
T a[2];
};
};
template <class T>
struct base_vector<T,3>{
union{
struct{T x,y,z;};
T a[3];
};
};
template <class T>
struct base_vector<T,4>{
union{
struct{T x,y,z,w;};
T a[4];
};
};
//子类Vector
template <class T, int N>
class Vector:public base_vector<T,N>{
public:
Vector()=default;
explicit Vector(initializer_list<T> l){
copy(begin(l), end(l), a);
}
using base_vector<T,N>::a;
T norm(){
T _norm=0;
for(int i=0;i<N;i++){
_norm+=a[i]*a[i];
}
return _norm;
}
void show_elements(){
switch (N) {//Fall through
case 4: cout<<"w="<<a[3]<<endl;
case 3: cout<<"z="<<a[2]<<endl;
case 2: cout<<"y="<<a[1]<<endl;
default:cout<<"x="<<a[0]<<endl;
}
}
T& operator[](int i){
return a[i];
}
Vector& operator+=(Vector &rhs){
for(int i=0;i<N;i++){
a[i]+=rhs[i];
}
return *this;
}
Vector operator+(Vector &rhs){
Vector ret{*this};
ret+=rhs;
return ret;
}
};
int main(){
Vector<int, 3> hello{1,1,1}, world{2,3,4};
auto hehe=hello+world;
hehe.show_elements();
cout<<"Norm is "<<hehe.norm()<<endl;
}