/
scpp_array.hpp
75 lines (56 loc) · 1.67 KB
/
scpp_array.hpp
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
/*
Safe C++, Or How to Avoid Most Common Mistakes in C++ Code
by Vladimir Kushnir, (OÕReilly).
Copyright 2012 Vladimir Kushnir, ISBN 9781449320935.
If you feel your use of code examples falls outside fair use or the
permission given above, feel free to contact us at permissions@oreilly.com.
*/
#ifndef __SCPP_ARRAY_HPP_INCLUDED__
#define __SCPP_ARRAY_HPP_INCLUDED__
#include "scpp_assert.hpp"
namespace scpp {
// Fixed-size array
template <typename T, unsigned N>
class array {
public:
typedef unsigned size_type;
// Most commonly used constructors:
array() {}
explicit array(const T& initial_value) {
for(size_type i=0; i<size(); ++i)
data_[i] = initial_value;
}
size_type size() const { return N; }
// Note: we do not provide a copy-ctor and assignment operator.
// we rely on default versions of these methods generated by the compiler.
T& operator [] (size_type index) {
SCPP_TEST_ASSERT(index < N,
"Index " << index << " must be less than " << N);
return data_[index];
}
const T& operator [] (size_type index) const {
SCPP_TEST_ASSERT(index < N,
"Index " << index << " must be less than " << N);
return data_[index];
}
// Accessors
T* begin() { return &data_[0]; }
const T* begin() const { return &data_[0]; }
// Returns pointer PAST the end of the array.
T* end() { return &data_[N]; }
const T* end() const { return &data_[N]; }
private:
T data_[N];
};
} // namespace scpp
template <typename T, unsigned N>
inline
std::ostream& operator << (std::ostream& os, const scpp::array<T,N>& a) {
for( unsigned i=0; i<a.size(); ++i ) {
os << a[i];
if( i + 1 < a.size() )
os << " ";
}
return os;
}
#endif // __SCPP_ARRAY_HPP_INCLUDED__