fork download
  1. #include <algorithm>
  2. #include <cstddef>
  3. #include <iostream>
  4. #include <iterator>
  5. #include <string>
  6.  
  7. class string_literal
  8. {
  9. char const* begin_;
  10. char const* end_;
  11. static constexpr std::size_t str_len(char const* begin, std::size_t len) {
  12. return *begin == 0? len: str_len(begin + 1, len + 1);
  13. }
  14. public:
  15. constexpr string_literal(char const* b)
  16. : begin_(b), end_(b + str_len(b, 0)) {
  17. }
  18. constexpr string_literal(char const* b, char const* e)
  19. : begin_(b), end_(e) {
  20. }
  21. constexpr char const* begin() const { return this->begin_; }
  22. constexpr char const* end() const { return this->end_; }
  23. bool operator== (std::string const& other) const {
  24. return other.size() == std::size_t(std::distance(begin_, end_))
  25. && std::equal(begin_, end_, other.begin());
  26. }
  27. bool operator!= (std::string const& other) const {
  28. return !(*this == other);
  29. }
  30. };
  31.  
  32. std::ostream& operator<< (std::ostream& out, string_literal const& s) {
  33. std::ostream::sentry cerberos(out);
  34. if (cerberos) {
  35. out << '\'';
  36. std::copy(s.begin(), s.end(), std::ostreambuf_iterator<char>(out));
  37. out << '\'';
  38. }
  39. return out;
  40. }
  41.  
  42. constexpr string_literal operator"" _sl(char const* begin, std::size_t)
  43. {
  44. return string_literal(begin);
  45. }
  46.  
  47. constexpr string_literal hello_1("hello"_sl);
  48. constexpr string_literal hello_2("hello");
  49.  
  50. int main()
  51. {
  52. std::cout << "hello\0world"_sl << '\n';
  53. std::cout << hello_1 << '\n';
  54. }
  55.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
'hello'
'hello'