本文介绍了重载向量<T>的输出流操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重载输出流运算符的推荐方法是什么?以下可以完成.如果操作符<

What is a recommended way to overload the output stream operator? The following can 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::const_iterator,需要声明为 typename std::vector::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.

类型、依赖类型和类型名称不能在评论中全部放完,所以这里是(顺便说一句.这是我的理解,我可能会离开一英里 - 如果是这样,请纠正我!)...

types, dependent types and typenameCan'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)将被视为非类型.要显式告诉编译器依赖名称是真实类型,您必须指定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,这也适用.即

This applies even if it is a typedef. i.e.

template <typename T>
void foo()
{
  typedef typename T::bob local_bob;
};

这样更清楚吗?

这篇关于重载向量&lt;T&gt;的输出流操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:51