Skip to content

Instantly share code, notes, and snippets.

@florianbehrens
Created March 12, 2019 11:24
Show Gist options
  • Save florianbehrens/48b0acc7f08c8119a9d245b80514d039 to your computer and use it in GitHub Desktop.
Save florianbehrens/48b0acc7f08c8119a9d245b80514d039 to your computer and use it in GitHub Desktop.
Static string implementation
#include <array>
#include <cassert>
template <std::size_t N>
class static_string
{
public:
using size_type = std::size_t;
using value_type = char;
using reference = char&;
using const_reference = const char&;
using iterator = typename std::array<char, N>::iterator;
using const_iterator = typename std::array<char, N>::const_iterator;
reference operator[](size_type pos) noexcept
{
return buf_[pos];
}
const_reference operator[](size_type pos) const noexcept
{
return buf_[pos];
}
reference front() noexcept
{
return buf_[0];
}
const_reference front() const noexcept
{
return buf_[0];
}
reference back() noexcept
{
return buf_[size_];
}
const_reference back() const noexcept
{
return buf_[size_];
}
char* data()
{
return buf_.data();
}
iterator begin() noexcept
{
return buf_.begin();
}
const_iterator begin() const noexcept
{
return buf_.begin();
}
const_iterator cbegin() const noexcept
{
return buf_.cbegin();
}
iterator end() noexcept
{
return buf_.begin() + size_;
}
const_iterator end() const noexcept
{
return buf_.begin() + size_;
}
const_iterator cend() const noexcept
{
return buf_.cbegin() + size_;
}
bool empty() const noexcept
{
return size_ == 0;
}
size_type size() const noexcept
{
return size_;
}
size_type max_size() const noexcept
{
return N;
}
void reserve(size_type n) const noexcept
{
assert(n <= N);
}
size_type capacity() const noexcept
{
return N;
}
void clear() noexcept
{
size_ = 0;
}
void push_back(const_reference value)
{
assert(size_ < N);
buf_[size_++] = value;
}
void pop_back() noexcept
{
size_ -= 1;
}
void resize(size_type n) const noexcept
{
assert(n <= N);
}
private:
std::array<char, N> buf_;
size_type size_{0};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment