我希望能够将任何内容附加std::vector<T>
到输出流。我找到了这段代码:
#ifndef DEBUG_H_
#define DEBUG_H_
#include <vector>
template < class T >
std::ostream& operator << (std::ostream& os, const std::vector<T>& v)
{
os << "[";
for (typename std::vector<T>::const_iterator ii = v.begin(); ii != v.end(); ++ii)
{
os << " " << *ii;
}
os << "]";
return os;
}
#endif /* DEBUG_H_ */
并放入标题中Debug.h
。如何在整个项目中使用此运算符?
编辑:我已经验证这在单元测试中有效:
#include "Debug.h"
TEST_F(AuxGTest, testVectorDebug) {
std::vector<int> vec(10, 42);
std::cout << "vec: " << vec << std::endl;
}
但是将它与 log4cxx 的日志语句一起使用是行不通的:
#include <log4cxx>
#include "Debug.h"
namespace Foo {
class Bar {
void foo() {
std::vector<int> vec(10, 42);
DEBUG("vec: " << vec);
}
}
}
这将导致以下编译器消息:
/usr/local/Cellar/log4cxx/0.10.0/include/log4cxx/helpers/messagebuffer.h:190:47: error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'