我正在开发一个模板图数据结构,它是 GraphNode 对象的 STL vector 。我定义了嵌套在 Graph 类中的 GraphNode 类,当我在 Graph 对象 Visual Studio 15 (C++) 报告的重载插入运算符内调用 GraphNode 对象的重载插入运算符时,
(30): warning C4346: 'myGraph<T>::myGraphNode': dependent name is not a type (30): note: prefix with 'typename' to indicate a type (30): error C2061: syntax error: identifier 'myGraphNode' (33): error C2805: binary 'operator <<' has too few parameters
template <typename T>
ostream& operator<<(ostream& strm, const myGraph<T>::myGraphNode& gn)
将单词 typename 添加到第二个形参
template <typename T>
ostream& operator<<(ostream& strm, typename const myGraph<T>::myGraphNode& gn)
编译器生成以下错误
(49): error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const myGraph<int>::myGraphNode' (or there is no acceptable conversion)
如果我输入 name const .... 或 const typename ...,我会得到同样的错误
为了完整起见,这里对本文的所有代码进行了一些简化。 感谢您的帮助
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef unsigned int uint;
template <typename T>
class myGraph {
public:
class myGraphNode {
public:
myGraphNode(T val = T());
T mData;
}; // end class myGraphNode
myGraph();
uint addGraphNode(T data);
vector<myGraphNode> mGraphNodes;
}; // end class myGraph
// myGraphNode
template <typename T>
myGraph<T>::myGraphNode::myGraphNode(T val) : mData(val) {}
template <typename T>
ostream& operator<<(ostream& strm, typename const myGraph<T>::myGraphNode& gn) {
strm << gn.mData << std::endl;
return strm;
}
// myGraph
template <typename T>
myGraph<T>::myGraph() {}
template <typename T>
uint myGraph<T>::addGraphNode(T data) {
myGraph<T>::myGraphNode node(data);
mGraphNodes.push_back(node);
}
template <typename T>
ostream& operator<<(ostream& strm, const myGraph<T>& g) {
for (uint i = 0; i < g.mGraphNodes.size(); ++i)
cout << g.mGraphNodes[i] << endl;
return strm;
} // end operator<<(...)
int main()
{
myGraph<int> g;
g.addGraphNode(3);
g.addGraphNode(5);
cout << g << endl;
return 0;
}
最佳答案
首先,参数声明的正确语法应该是
template <typename T>
ostream& operator<<(ostream& strm, const typename myGraph<T>::myGraphNode& gn)
// ~~~~~ ~~~~~~~~
引用here了解更多信息。
其次,通过上述声明,当尝试在 operator<<
中调用它时对于 myGraph<T>
喜欢 cout << g.mGraphNodes[i] << endl;
, T
无法推断,因为 non-deduced contexts) :
The nested-name-specifier (everything to the left of the scope resolution operator ::) of a type that was specified using a qualified-id:
这意味着,您必须为其显式指定模板参数,例如
operator<<<T>(strm, g.mGraphNodes[i]);
// ~~~
但是很丑。对于您的情况,您只需实现 operator<<
对于 myGraph<T>
喜欢
template <typename T>
ostream& operator<<(ostream& strm, const myGraph<T>& g) {
for (uint i = 0; i < g.mGraphNodes.size(); ++i)
cout << g.mGraphNodes[i].mData << endl;
return strm;
}
顺便说一句:您应该给出 myGraph<T>::addGraphNode
的返回值.
关于c++ - 嵌套模板类和全局命名空间中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49587548/