Boost.Locale
any_string.hpp
1//
2// Copyright (c) 2023 Alexander Grund
3//
4// Distributed under the Boost Software License, Version 1.0.
5// https://www.boost.org/LICENSE_1_0.txt
6
7#ifndef BOOST_LOCALE_DETAIL_ANY_STRING_HPP_INCLUDED
8#define BOOST_LOCALE_DETAIL_ANY_STRING_HPP_INCLUDED
9
10#include <boost/locale/config.hpp>
11#include <boost/assert.hpp>
12#include <boost/utility/string_view.hpp>
13#include <memory>
14#include <stdexcept>
15#include <string>
16
18namespace boost { namespace locale { namespace detail {
20 class any_string {
21 struct BOOST_SYMBOL_VISIBLE base {
22 virtual ~base() = default;
23 virtual base* clone() const = 0;
24
25 protected:
26 base() = default;
27 base(const base&) = default;
28 base(base&&) = delete;
29 base& operator=(const base&) = default;
30 base& operator=(base&&) = delete;
31 };
32 template<typename Char>
33 struct BOOST_SYMBOL_VISIBLE impl : base {
34 explicit impl(const boost::basic_string_view<Char> value) : s(value) {}
35 impl* clone() const override { return new impl(*this); }
36 std::basic_string<Char> s;
37 };
38
39 std::unique_ptr<const base> s_;
40
41 public:
42 any_string() = default;
43 any_string(const any_string& other) : s_(other.s_ ? other.s_->clone() : nullptr) {}
44 any_string(any_string&&) = default;
45 any_string& operator=(any_string other) // Covers the copy and move assignment
46 {
47 s_.swap(other.s_);
48 return *this;
49 }
50
51 template<typename Char>
52 void set(const boost::basic_string_view<Char> s)
53 {
54 BOOST_ASSERT(!s.empty());
55 s_.reset(new impl<Char>(s));
56 }
57
58 template<typename Char>
59 std::basic_string<Char> get() const
60 {
61 if(!s_)
62 throw std::bad_cast();
63 return dynamic_cast<const impl<Char>&>(*s_).s;
64 }
65 };
66
67}}} // namespace boost::locale::detail
68
70
71#endif