下面的示例是我遇到的模板问题的蒸馏版本 - 请参阅下面的编译错误。如何重载operator <<以输出在模板内定义的向量?
#include <iostream>
#include <vector>
template <class T> struct S
{
typedef std::vector<T> SVec;
};
template <class T> std::ostream& operator<<(std::ostream& OS, const S<T>::SVec& X)
{
for (const auto& e: X) OS << e << ' ';
return OS;
}
int main()
{
S<int>::SVec v;
std::cout << v << std::endl;
}
编译器输出:
g++ -g -Wall -O4 -std=c++11 -c tc041.cpp
tc041.cpp:22:69: error: need ‘typename’ before ‘S<T>::SVec’ because ‘S<T>’ is a dependent scope
template <class T> std::ostream& operator<<(std::ostream& OS, const S<T>::SVec& X)
等等 - 数百行。 我的编译器 - g ++ 5.2.1,OS - Xubuntu 4.2.0。
如何使该运算符能够正确编译?
错误消息其实是非常字面,尽管它需要一些更多的知识去了解它。 –