-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate_vector.hh
75 lines (67 loc) · 2.66 KB
/
template_vector.hh
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
#ifndef VECTOR_IT_H
#define VECTOR_IT_H
#include <functional>
#include <iostream>
#include <memory>
#include <vector>
namespace template_vect {
template <typename T> class TemplateVector {
public:
explicit TemplateVector(int n = 100);
// First size_t is size of array paramter arr; second is size of the copy,
// which can be smaller. The first could be a template parameter, but then
// the class definition and all ctors would require it. Two parameters also
// would complicate assignment operators.
TemplateVector(const T arr[], size_t sz1, size_t sz2);
TemplateVector(T arr[], size_t sz1, size_t sz2);
TemplateVector(const ::std::vector<T> &v);
TemplateVector(const TemplateVector<T> &v) = delete;
TemplateVector(TemplateVector &&v);
TemplateVector &operator=(TemplateVector &&v) = default;
int ub() const { return (size_ - 1); }
T &operator[](int i);
const T &operator[](int i) const;
typedef T *iterator;
iterator begin() const { return &p_[0]; }
iterator end() const { return &p_[size_]; }
iterator operator++() const { return &p_[cursor_++]; };
iterator operator--() const { return &p_[cursor_--]; };
// The function is not found by the linker if not placed in the header.
// See comment in template_stack.hh.
friend ::std::ostream &operator<<(::std::ostream &out,
const TemplateVector<T> &tv) {
for (T *tvit = tv.begin(); tvit != tv.end(); tvit++) {
out << *tvit << ", ";
}
return out;
}
// clang-format off
// https://stackoverflow.com/questions/9787593/implicit-type-conversion-with-template
// No 'static' here:
// template_vector.hh:35:79: error: storage class specifiers invalid in friend
// function declarations friend static void tvassign(TemplateVector<U> &uvec,
// TemplateVector<V> &vvec);
// clang-format on
template <typename U, typename V>
friend void tvassign(TemplateVector<U> &uvec, TemplateVector<V> &vvec);
template <typename U, typename V>
friend bool operator==(const TemplateVector<U> &tv1,
const TemplateVector<V> &tv2);
private:
std::unique_ptr<T[]> p_;
size_t size_;
// Making cursor_ mutable allows the iterators to be const, thus providing a
// way to view the container without the possibility of modifying it.
mutable int cursor_ = 0;
};
// http://www.cplusplus.com/reference/stdexcept/invalid_argument/
class assignment_error : public std::logic_error {
public:
explicit assignment_error(const std::string &what_arg)
: std::logic_error(what_arg) {}
explicit assignment_error(const char *what_arg)
: std::logic_error(what_arg) {}
};
} // namespace template_vect
#include "template_vector_impl.hh"
#endif