微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – boost :: format和定制打印std容器

我在我的命名空间ns中有一个函数可以帮助我打印STL容器.例如:
template <typename T>
std::ostream& operator<<(std::ostream& stream,const std::set<T>& set)
{
    stream << "{";
    bool first = true;
    for (const T& item : set)
    {
        if (!first)
            stream << ",";
        else
            first = false;
        stream << item;
    }
    stream << "}";
    return stream;
}

这对于用操作符<<直:

std::set<std::string> x = { "1","2","3","4" };
std::cout << x << std::endl;

但是,使用boost :: format是不可能的:

std::set<std::string> x = { "1","4" };
boost::format("%1%") % x;

问题是相当明显的:Boost不知道我希望它使用我的自定义运算符<<打印与我的命名空间无关的类型.除了在boost / format / Feed_args.hpp中添加使用声明之外,是否有一种方便的方式来使boost :: format找到我的运算符<?

解决方法

我认为最干净的方法是为您要覆盖的每个操作符在您自己的命名空间中提供一个薄的包装器.对于你的情况,它可以是:
namespace ns
{
    namespace wrappers
    {
        template<class T>
        struct out
        {
            const std::set<T> &set;

            out(const std::set<T> &set) : set(set) {}

            friend std::ostream& operator<<(std::ostream& stream,const out &o)
            {
                stream << "{";
                bool first = true;
                for (const T& item : o.set)
                {
                    if (!first)
                        stream << ",";
                    else
                        first = false;
                    stream << item;
                }
                stream << "}";
                return stream;
            }
        };
    }

    template<class T>
    wrappers::out<T> out(const std::set<T> &set)
    {
        return wrappers::out<T>(set);
    }
}

然后使用它:

std::cout << boost::format("%1%") % ns::out(x);

原文地址:https://www.jb51.cc/c/116265.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐