c++20: 这么好用的特性为什么不早点出
为自建的Zstr字符串库支持任...
为自建的Zstr字符串库支持任意容器打印:
#include "zstr.hpp"
#include <map>
#include <tuple>
#include <vector>
int main(){
using namespace std;
map<float, vector<pair<Zstr, int>>> t;
t[1.2] = {{"Zstr", 2}, {"ZZZZ", 3}};
t[114] = {{"支持循环嵌套", 0}};
tuple<int, map<float, vector<pair<Zstr, int>>>> test =
{1, t};
cout << Zstr::from(test) << endl;
}
输出:
<1, {1.2: [<Zstr: 2>, <ZZZZ: 3>], 114: [<支持循环嵌套: 0>]}>
c++在很早就已经支持了类型萃取
但是老写法简直是依托
concept拯救了这一点
以下是Zstr的具体实现,它使用concept进行模板匹配,从而输出正确的结果
Zstr.hpp:
#pragma once
#include <stringzilla/stringzilla.hpp>
#include <iostream>
#include <string>
#include <boost/regex.hpp>
#include <boost/locale/encoding.hpp>
#include <type_traits>
#include <ranges>
#include <unordered_set>
#include <tuple>
#include <format>
namespace __ZSTR_BASE {
template <typename T>
concept IsFormattable = requires(const T& t) {
typename std::formatter<T>;
{ std::formatter<T>{}.parse(std::declval<std::format_parse_context&>()) }
-> std::same_as<std::format_parse_context::iterator>;
{ std::formatter<T>{}.format(t, std::declval<std::format_context&>()) }
-> std::same_as<std::format_context::iterator>;
};
template <typename T>
constexpr bool IsFormattable_v = IsFormattable<T>;
template<typename T>
concept IsPair = requires(T t) {
{ t.first } -> std::convertible_to<const typename std::remove_cvref_t<T>::first_type&>;
{ t.second } -> std::convertible_to<const typename std::remove_cvref_t<T>::second_type&>;
} && requires {
requires std::same_as<
std::remove_cvref_t<T>,
std::pair<
typename std::remove_cvref_t<T>::first_type,
typename std::remove_cvref_t<T>::second_type
>
>;
};
template<typename T>
concept IsMap =
std::convertible_to<T, std::map<T, T>>;
template<typename T>
concept IterableNotFormattable =
!IsFormattable<T> && std::ranges::input_range<T>;
template<typename T>
concept Can_Zstr_From =
IsFormattable<T> ||
IsPair<T> ||
IterableNotFormattable<T>;
template <template <typename...> class Template, typename T>
struct is_template_instance : std::false_type {};
template <template <typename...> class Template, typename... Args>
struct is_template_instance<Template, Template<Args...>> : std::true_type {};
template <typename T>
constexpr bool Is_map_or_unordered_map_v =
is_template_instance<std::map, T>::value ||
is_template_instance<std::unordered_map, T>::value;
template<typename T>
concept IsMapPair = IsPair<T> && requires {
requires std::is_const_v<typename std::remove_cvref_t<T>::first_type>;
};
template<typename T>
constexpr bool IsMapPair_v = IsMapPair<T>;
template<typename T>
struct is_set : std::false_type {};
template<typename Key, typename Compare, typename Alloc>
struct is_set<std::set<Key, Compare, Alloc>> : std::true_type {};
template<typename T>
struct is_unordered_set : std::false_type {};
template<typename Key, typename Hash, typename KeyEqual, typename Alloc>
struct is_unordered_set<std::unordered_set<Key, Hash, KeyEqual, Alloc>> : std::true_type {};
template<typename T>
concept Is_set_or_unordered_set =
is_set<T>::value ||
is_unordered_set<T>::value;
template<typename T>
constexpr bool Is_set_or_unordered_set_v = Is_set_or_unordered_set<T>;
template<typename T>
struct __IsTuple : std::false_type {};
template<typename... Args>
struct __IsTuple<std::tuple<Args...>> : std::true_type {};
template<typename T>
concept IsTuple = __IsTuple<T>::value;
template<typename T>
constexpr bool IsTuple_v = IsTuple<T>;
}
using Zstr_view = ashvardanian::stringzilla::string_view;
class Zstr: public ashvardanian::stringzilla::string{
public:
using ashvardanian::stringzilla::string::string;
Zstr(char c){
this->push_back(c);
}
std::vector<Zstr> find_all_regex(const std::string &pattern) const {
std::vector<Zstr> matches;
boost::regex re(pattern);
boost::cregex_iterator it(this->c_str(), this->c_str() + this->size(), re);
boost::cregex_iterator end;
const char* start_ptr = this->c_str();
for (; it != end; ++it) {
const boost::cmatch& match = *it;
const char* match_start = match[0].first;
const char* match_end = match[0].second;
if (match_start == match_end)
continue;
std::size_t pos = static_cast<std::size_t>(match_start - start_ptr);
std::size_t len = static_cast<std::size_t>(match_end - match_start);
matches.push_back(Zstr(std::string(this->substr(pos, len))));
}
return matches;
}
Zstr replace_all_regex(const std::string &pattern, Zstr_view replacement) const {
std::string s = this->c_str();
std::string result = boost::regex_replace(s, boost::regex(pattern), replacement);
return Zstr(result.c_str());
}
Zstr to_encoding(const std::string& to_encoding, const std::string& from_encoding = "UTF-8") const {
try {
std::string current_str(this->c_str(), this->size());
std::string converted_str = boost::locale::conv::between(current_str, to_encoding, from_encoding);
return Zstr(converted_str.data(), converted_str.size());
}
catch (const boost::locale::conv::conversion_error& e) {
throw std::runtime_error("Encoding conversion error: " + std::string(e.what()));
}
}
template<__ZSTR_BASE::IsFormattable Formattable>
static Zstr from(const Formattable& arg) {
return std::format("{}", arg);
}
template<__ZSTR_BASE::IterableNotFormattable TRanges>
static Zstr from(const TRanges& arg) {
char left_c = '[', right_c = ']';
if constexpr (
__ZSTR_BASE::Is_map_or_unordered_map_v<TRanges> || __ZSTR_BASE::Is_set_or_unordered_set_v<TRanges>
){
left_c = '{', right_c = '}';
}
Zstr ostr = left_c;
ostr += join(arg, ", ") + right_c;
return ostr;
}
template<__ZSTR_BASE::IsPair TPair>
static Zstr from(const TPair& arg) {
Zstr ostr = Zstr::from(arg.first);
ostr += Zstr(": ") + Zstr::from(arg.second);
if constexpr (! __ZSTR_BASE::IsMapPair_v<TPair>){
ostr.insert(ostr.begin(), '<');
ostr.push_back('>');
}
return ostr;
}
template<__ZSTR_BASE::IsTuple TTuple>
static Zstr from(const TTuple& arg) {
Zstr ostr = "<";
std::apply([&](const auto&... elements) {
((ostr += (ostr.size() > 1 ? ", " : "") + Zstr::from(elements)), ...);
}, arg);
ostr += ">";
return ostr;
}
template<std::ranges::input_range T>
static Zstr join(const T &arg, Zstr_view split) {
Zstr ostr;
auto begin = std::ranges::begin(arg);
auto end = std::ranges::end(arg);
if (begin == end) return ostr;
auto current = begin;
if constexpr (__ZSTR_BASE::Can_Zstr_From<decltype(*current)>) {
ostr += Zstr::from(*current);
} else {
ostr += Zstr(*current);
}
++current;
for (; current != end; ++current) {
ostr += split;
if constexpr (__ZSTR_BASE::Can_Zstr_From<decltype(*current)>) {
ostr += Zstr::from(*current);
} else {
ostr += Zstr(*current);
}
}
return ostr;
}
inline Zstr operator*(size_t mul) const {
Zstr result;
const size_t len = this->size();
if (len == 0 || mul == 0) {
return result;
}
result.reserve(len * mul);
for (size_t i = 0; i < mul; ++i) {
result += *this;
}
return result;
}
inline std::string to_std_string(){
return std::string(this->data(), this->size());
}
};
inline std::istream& operator>>(std::istream& is, Zstr& zstr) {
zstr.clear();
char c;
while (is.get(c) && !std::isspace(c))
zstr.push_back(c);
return is;
}
inline std::istream& getline(std::istream& is, Zstr& zstr, char delim = '\n') {
zstr.clear();
char c;
while (is.get(c) && c != delim)
zstr.push_back(c);
return is;
}
Zstr inline operator+(const char* left, const Zstr& right) {
Zstr ostr = left;
ostr.append(right);
return ostr;
}
Zstr inline operator+(const Zstr& left, const char* right) {
Zstr ostr = left;
ostr.append(right);
return ostr;
}
namespace std {
template<>
struct formatter<Zstr> {
constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
// 格式化 Zstr 对象
template<typename FormatContext>
auto format(const Zstr& zstr, FormatContext& ctx) const -> decltype(ctx.out()) {
return std::format_to(ctx.out(), "{}", zstr.c_str());
}
};
} // namespace std