Tra*_*kel 10 c++ boost namespaces boost-format
我的命名空间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;
}
Run Code Online (Sandbox Code Playgroud)
这适用于operator <<直接打印:
std::set<std::string> x = { "1", "2", "3", "4" };
std::cout << x << std::endl;
Run Code Online (Sandbox Code Playgroud)
但是,使用boost::format是不可能的:
std::set<std::string> x = { "1", "2", "3", "4" };
boost::format("%1%") % x;
Run Code Online (Sandbox Code Playgroud)
问题是相当明显的:Boost不知道我希望它使用我的自定义operator <<来打印与我的命名空间无关的类型.在添加using声明之外boost/format/feed_args.hpp,有没有方便的方法来boost::format寻找我的operator <<?
我实际使用的解决方案与Answeror非常相似,但它适用于任何事情:
namespace ns
{
template <typename T>
class FormatWrapper
{
public:
explicit FormatWrapper(const T& x) :
ref(x)
{ }
friend std::ostream& operator<<(std::ostream& stream,
const FormatWrapper<T>& self
)
{
// The key is that operator<< is name lookup occurs inside of `ns`:
return stream << self.ref;
}
private:
const T& ref;
};
template <typename T>
FormatWrapper<T> Formatable(const T& x)
{
return FormatWrapper<T>(x);
}
}
Run Code Online (Sandbox Code Playgroud)
用法是:
boost::format("%1%") % Formatable(x);
Run Code Online (Sandbox Code Playgroud)
小智 4
我认为最干净的方法是在您自己的命名空间中为您想要覆盖的每个运算符提供一个薄包装器。对于您的情况,它可以是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
std::cout << boost::format("%1%") % ns::out(x);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1368 次 |
| 最近记录: |