我越来越多地接触通用模板,这意味着,我仍然不是专家。我将实现对象和指针模板(C ++特别版第13.5节)的想法改编为我的图形实现,但我现在已经困住了几天。
我有三个头文件,并注释掉每个方法声明和实现,以便更接近以下错误:
在DirectedGraph.cpp中包含的文件中:8:0: DirectedGraph.h:16:48:错误:'DirectedGraph'不是模板类型 模板类DirectedGraph:public Graph
DirectedGraph.h:45:22:错误:'DirectedGraph'不是类模板 模板<> class DirectedGraph:public Graph
DirectedGraph.h:45:50:错误:'DirectedGraph'不是模板类型 模板<> class DirectedGraph:public Graph
DirectedGraph.h:74:48:错误:'DirectedGraph'不是类模板 模板类DirectedGraph:private Graph
DirectedGraph.h:74:80:错误:'DirectedGraph'不是模板类型
// Graph.h
template<class V_type, class E_type> class Graph
{ };
template<> class Graph<void *, void *>
{ };
template<class V_type, class E_type> class Graph<V_type *, E_type *> : public Graph<void *, void *>
{ };
// Vertex.h
template<class V_type, class E_type> class Vertex
{
friend class DirectedGraph;
};
template<> class Vertex<void *, void *>
{
friend class DirectedGraph;
};
template<class V_type, class E_type> class Vertex<V_type *, E_type *> : private Vertex<void *, void *>
{
friend class DirectedGraph;
};
// DirectedGraph.h
template<class V_type, class E_type> class DirectedGraph : public ggraph::Graph<V_type, E_type>
{ };
template<> class DirectedGraph<void *, void *> : public ggraph::Graph<void *, void *>
{ };
template<class V_type, class E_type> class DirectedGraph<V_type *, E_type *> : private ggraph::Graph<void *, void *>
{ };
答案 0 :(得分:0)
问题中的代码来自DirectedGraph
ggraph::Graph
,因此必须至少将Graph
放在ggraph
命名空间中。
尝试:
namespace ggraph
{
// Graph.h
template<class V_type, class E_type> class Graph
{ };
template<> class Graph<void *, void *>
{ };
template<class V_type, class E_type> class Graph<V_type *, E_type *> : public Graph<void *, void *>
{ };
// Vertex.h
template<class V_type, class E_type> class Vertex
{
template <V_type, E_type> friend class DirectedGraph;
};
template<> class Vertex<void *, void *>
{
template <class V_type = void*, class E_type = void*> friend class DirectedGraph;
};
template<class V_type, class E_type> class Vertex<V_type *, E_type *> : private Vertex<void *, void *>
{
template <void*, void*> friend class DirectedGraph;
};
// DirectedGraph.h
template<class V_type, class E_type> class DirectedGraph : public ggraph::Graph<V_type, E_type>
{ };
template<> class DirectedGraph<void *, void *> : public ggraph::Graph<void *, void *>
{ };
template<class V_type, class E_type> class DirectedGraph<V_type *, E_type *> : private ggraph::Graph<void *, void *>
{ };
} // namespace ggraph