【发布时间】:2012-05-30 00:14:14
【问题描述】:
我的命名空间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;
}
这非常适合直接使用operator << 打印:
std::set<std::string> x = { "1", "2", "3", "4" };
std::cout << x << std::endl;
但是,使用boost::format 是不可能的:
std::set<std::string> x = { "1", "2", "3", "4" };
boost::format("%1%") % x;
问题很明显:Boost 不知道我希望它使用我的自定义 operator << 来打印与我的命名空间无关的类型。除了在boost/format/feed_args.hpp 中添加using 声明之外,有没有一种方便的方法可以让boost::format 查找我的operator <<?
【问题讨论】:
-
我强烈建议您看看this question,因为它基本上可以满足您的需求。不过,由于您的实际问题不同(关于
operator<<),我不会投票关闭作为重复项。 -
@Xeo:我的实际代码使用非常相似的方法来打印任何容器。无论如何,问题不在于如何使用
operator <<打印容器,而在于如何使同样的重载适用于 Koenig 不做我想做的事情。
标签: c++ boost namespaces boost-format