#include <iostream>
#include <sstream>
// ============================================== Rudimentary TDD-Support
#define SHOW_(expect, ...)\
do {\
std::ostringstream result;\
result.copyfmt(std::cout);\
result << (__VA_ARGS__);\
const bool ok = (result.str() == expect);\
std::cout << (ok ? '*' : '!') << ' '\
<< __FUNCTION__ << ':' << __LINE__ << '\t'\
<< #__VA_ARGS__ << " --> " << result.str();\
if (!ok) {\
std::cout << " != " << expect;\
}\
std::cout << std::endl;\
}\
while (0)
// =======================================================================
#include "my_static_vector.h"
void constructor_test() {
my::static_vector<int, 10> obj1;
SHOW_("48", sizeof obj1);
my::static_vector<double, 3> obj2;
SHOW_("32", sizeof obj2);
}
void max_size_test() {
my::static_vector<int, 10> obj1;
SHOW_("10", obj1.max_size());
my::static_vector<double, 3> obj2;
SHOW_("3", obj2.max_size());
}
void push_pop_back_test() {
my::static_vector<int, 10> obj1;
obj1.push_back(123);
SHOW_("123", obj1.back());
obj1.push_back(-1);
SHOW_("-1", obj1.back());
obj1.pop_back();
SHOW_("123", obj1.back());
}
int main() {
constructor_test();
max_size_test();
push_pop_back_test();
std::cout << "*** TESTING COMPLETED ***" << std::endl;
}
#ifndef MY_STATIC_VECTOR_H
#define MY_STATIC_VECTOR_H
#include <cassert>
namespace my {
/*
* A class much like `std::vector` but with pre-allocated space
* in a maximum size. As for `std::vector` this container is empty
* at the beginning. Need to be added before they can be accessed.
*/
template <typename T, std::size_t N>
class static_vector {
public:
using value_type = T;
using size_type = decltype(N);
static size_type max_size() { return N; }
static_vector() : filled_(data_) {}
void push_back(T const& item_to_append) {
assert(filled_ < &data_[max_size()]);
*(filled_++) = item_to_append;
}
value_type& back() {
assert(filled_ > &data_[0]);
assert(filled_ <= &data_[max_size()]);
return *(filled_-1);
}
value_type const& back() const {
assert(filled_ > &data_[0]);
assert(filled_ <= &data_[max_size()]);
return *(filled_-1);
}
void pop_back() {
assert(filled_ > &data_[0]);
--filled_;
}
private:
value_type data_[N];
value_type* filled_;
};
} // namespace
#endif // include guard