为vector <T>重载输出流运算符

Leo*_*nid 15 c++ templates vector operator-overloading

什么是重载输出流操作符的推荐方法?以下无法完成.如果没有为类型T定义operator <<,则编译将失败.

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:它确实编译,问题是无关的,并在命名空间.谢谢你的帮助.

Jas*_*son 10

这就是你想要的:

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;
}
Run Code Online (Sandbox Code Playgroud)

你先忘了std :: ostream

你把后一个额外的空间[os << "[".

而你typename之前需要std::vector<T>::const_iterator


Nim*_*Nim 7

你真的尝试过这段代码了吗?它通过一个小的调整在gcc上正常工作std::vector<T>::const_iterator,需要声明为typename std::vector<T>::const_iterator

使用std :: copy和std :: ostream_iterator可能会更好.

编辑:类型,依赖类型和类型名称 不能在评论中适应所有,所以这里(顺便说一句.这是我的理解,我可以在一个国家英里 - 如果是这样,请纠正我!)...

我认为最好用一个简单的例子来解释.

我们假设你有一个函数foo

template <typename T>
void foo()
{
  T::bob * instofbob; // this is a dependent name (i.e. bob depends on T)
};
Run Code Online (Sandbox Code Playgroud)

看起来没问题,通常你可以这样做

class SimpleClass
{
  typedef int bob;
};
Run Code Online (Sandbox Code Playgroud)

并致电

foo<SimpleClass>(); // now we know that foo::instofbob is "int"
Run Code Online (Sandbox Code Playgroud)

再次,似乎是自我解释,然而一些nuser出现并做到这一点

class IdiotClass
{
  static int bob;
};
Run Code Online (Sandbox Code Playgroud)

现在

foo<IdiotClass>(); // oops, 
Run Code Online (Sandbox Code Playgroud)

你现在拥有的是一个表达式(乘法),因为IdiotClass :: bob解析为非类型!

对于人类来说,很明显这是愚蠢的,但是编译器无法区分类型与非类型,并且默认情况下在C++中(我认为这是编译器不同的地方),所有合格的相关名称(即T) :: bob)将被视为非类型.要明确告诉编译器依赖名称是实际类型,您必须指定typename关键字 -

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!)
};
Run Code Online (Sandbox Code Playgroud)

即使它是a,这也适用typedef.即

template <typename T>
void foo()
{
  typedef typename T::bob local_bob;
};
Run Code Online (Sandbox Code Playgroud)

那更清楚吗?