我希望能够打印正则表达式。出于正当理由,std::regex
没有保留文本正则表达式的副本,因此我们必须自己包装它。然而,简单的聚合非常冗长。有推荐的做法吗?如下所述,公共继承是否存在令人讨厌的问题?
#include <iomanip>
#include <iostream>
#include <string>
#include <regex>
template <
class CharT,
class Traits = std::regex_traits<CharT>
>
class basic_pp_regex
: public std::basic_regex<CharT, Traits>
{
public:
using self = basic_pp_regex;
using super = std::basic_regex<CharT, Traits>;
template <typename... Args>
basic_pp_regex(std::string pretty, Args&&... args)
: super{pretty, std::forward<Args>(args)...}
, _pretty{std::move(pretty)}
{}
basic_pp_regex(basic_pp_regex const&) = default;
basic_pp_regex(basic_pp_regex&&) = default;
// The default regex matches nothing.
basic_pp_regex()
: basic_pp_regex{"$."}
{}
friend
std::ostream& operator<<(std::ostream& o, self const& s)
{
return o << std::quoted(s._pretty, '/');
}
private:
std::string _pretty;
};
using pp_regex = basic_pp_regex<char>;
int main()
{
auto re = pp_regex("/foo");
auto s = "/root/foo/bar";
std::cout << s << " ~ " << re << " = " << std::regex_search(s, re) << '\n';
}
给出:
/root/foo/bar ~ /\/foo/ = 1