rosa/inc/tmp/stringview.h

53 lines
1.3 KiB
C
Raw Normal View History

2021-05-10 16:14:24 +00:00
#ifndef TMP_STRINGVIEW_H
#define TMP_STRINGVIEW_H
/**
* @file tmp/stringview.h"
* @brief partial implementation of C++17 std::string_view
*
* see: https://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c
* see: https://stackoverflow.com/a/20170989
* string_view is from "static_string" class
* to be replaced by std::string_view as soon as possible
*
* Adapted, minimal C++ version supported now C++11
*/
#include <stdexcept>
namespace tmp {
class string_view {
char const* const _p;
std::size_t const _sz;
public:
using const_iterator = char const*;
template<std::size_t N>
constexpr string_view(char const(&a)[N]) noexcept: _p(a), _sz(N-1) {}
constexpr string_view(char const*p, std::size_t N) noexcept: _p(p), _sz(N) {}
constexpr char const*data() const noexcept {return _p;}
constexpr std::size_t size() const noexcept {return _sz;}
constexpr const_iterator begin() const noexcept {return _p;}
constexpr const_iterator end() const noexcept {return _p + _sz;}
constexpr char operator[](std::size_t n) const {
return n < _sz? _p[n] : throw std::out_of_range("string_view");
}
explicit operator std::string() const { return {_p, _sz}; }
};
template<typename Ostream>
inline Ostream&operator<<(Ostream &os, string_view const&s) {
os.write(s.data(), s.size());
return os;
}
}
#endif