用于向量< T>的过载输出流算子 [英] Overloading output stream operator for vector<T>
问题描述
建议如何重载输出流运算子?以下可以不做。如果操作符<<
What is a recommended way to overload the output stream operator? The following can not be done. It is expected that compilation will fail if the operator << is not defined for a type T.
template < class T >
inline std::ostream& operator << (std::ostream& os, const std::vector<T>& v)
{
os << "[";
for (std::vector<T>::const_iterator ii = v.begin(); ii != v.end(); ++ii)
{
os << " " << *ii;
}
os << " ]";
return os;
}
编辑:它编译,问题是不相关的,感谢您的协助。
It does compile, the problem was unrelated and was in the namespace. Thanks for assistance.
推荐答案
您真的尝试过这段程式码吗?它在gcc上工作良好,有一个小的调整 std :: vector< T> :: const_iterator
,需要声明为 typename std :: vector< T> :: const_iterator
Did you actually try this code? It works fine on gcc with a small tweak std::vector<T>::const_iterator
, needs to be declared as typename std::vector<T>::const_iterator
使用std :: copy和std :: ostream_iterator可能会更好。
You may be better off with using std::copy and std::ostream_iterator.
EDIT:类型,依赖类型和类型名
无法在注释中使用,所以这里(btw。这是我的理解和我)
types, dependent types and typename Can't fit it all in the comments, so here goes (btw. this is my understanding and I could be off by a country mile - if so please correct me!)...
我认为这是最好的解释一个简单的例子..
I think this is best explained with a simple example..
让我们假设你有一个函数foo
Let's assume you have a function foo
template <typename T>
void foo()
{
T::bob * instofbob; // this is a dependent name (i.e. bob depends on T)
};
看起来不错,通常你可以这样做
Looks okay, and typically you may do this
class SimpleClass
{
typedef int bob;
};
并呼叫
foo<SimpleClass>(); // now we know that foo::instofbob is "int"
一些nuser来,这是
Again, seems self explanatory, however some nuser comes along and does this
class IdiotClass
{
static int bob;
};
现在
foo<IdiotClass>(); // oops,
现在你已经是一个表达式(乘法),因为IdiotClass :: bob解析为一个非类型!
What you have now is an expression (multiplication) as IdiotClass::bob resolves to a non-type!
对于人类来说,很明显这是愚蠢的,但是编译器没有办法区分类型和非类型,在C ++中(我认为这是编译器不同的地方),所有相关名称(即T :: bob)将被视为 em>。要显式地 告诉编译器依赖名称是一个真实类型,您必须指定 typename
关键字 -
To the human, it's obvious that this is stupid, but the compiler has no way of differentiating between types vs. non-types, and by default in C++ (and I think this is where compilers differ), all qualified dependent names (i.e. T::bob) will be treated as non-type. To explicitly tell the compiler that the dependent name is a real type, you must specify the typename
keyword -
template <typename T>
void foo()
{
typedef typename T::bob *instofbob; // now compiler is happy, it knows to interpret "bob" as a type (and will complain otherwise!)
};
即使它是 typedef
。即
template <typename T>
void foo()
{
typedef typename T::bob local_bob;
};
是否更清楚?
这篇关于用于向量< T>的过载输出流算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!