C++ 在C++;模板,是否允许返回具有特定类型参数的对象?
当我有一个具有特定类型参数的模板时,函数是否可以返回同一模板但具有不同类型的对象?换句话说,是否允许以下情况C++ 在C++;模板,是否允许返回具有特定类型参数的对象?,c++,templates,C++,Templates,当我有一个具有特定类型参数的模板时,函数是否可以返回同一模板但具有不同类型的对象?换句话说,是否允许以下情况 template<class edgeDecor, class vertexDecor, bool dir> Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const { /* Construc
template<class edgeDecor, class vertexDecor, bool dir>
Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool
print = false) const
{
/* Construct new Graph with apropriate decorators */
Graph<edgeDecor,int,dir> span = new Graph<edgeDecor,int,dir>();
/* ... */
return span;
};
模板
图:Dijkstra(顶点s,布尔)
打印=假)常数
{
/*用适当的修饰符构造新图*/
图span=新图();
/* ... */
返回跨度;
};
如果这是不允许的,我怎么能完成同样的事情呢?这当然是可能的。对我来说,上述代码似乎有效允许。对代码示例的一些更正:
template<class edgeDecor, class vertexDecor, bool dir>
Graph<edgeDecor,int,dir> *Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool
print = false) const
{
/* Construct new Graph with apropriate decorators */
Graph<edgeDecor,int,dir> *span = new Graph<edgeDecor,int,dir>();
/* ... */
return span;
};
模板
图*图::Dijkstra(顶点s,布尔
打印=假)常数
{
/*用适当的修饰符构造新图*/
图形*span=新图形();
/* ... */
返回跨度;
};
事实上,你可以返回你想要的任何东西。您甚至可以返回一些取决于模板参数的内容:
namespace result_of
{
template <class T>
struct method { typedef T type; };
template <class T>
struct method<T&> { typedef T type; }
template <class T>
struct method<T*> { typedef T type; }
template <class T, class A>
struct method< std::vector<T,A> > { typedef T type; }
}
template <class T>
typename result_of::method<T>::type method(const T&) { /** **/ };
的命名空间结果
{
模板
结构方法{typedef T type;};
模板
结构方法{typedef T type;}
模板
结构方法{typedef T type;}
模板
结构方法为什么?如果您要强制其他所有内容都是
int
,为什么不干脆放弃中间的模板参数并完成它呢?@potatosatter:它编译得很好,我还没有达到可以运行整个过程的程度@gman:我只希望这一个函数是int
,在图的其余部分中,它可能是其他任何东西。还是我误解了你?@agnel kurian按值返回图表的副本不合适吗?或者我必须始终使用带有new
关键字的指针?您必须使用带有new
关键字的指针。返回副本没问题。@agnel返回本地指针不是个好主意。我认为最好还是返回一个副本,但创建新的图形,如下所示:graph span=graph::graph()@agnel kurian:所以如果我使用new,我必须按照你建议的方式来做?@draco ater:这是否等同于说Graph::Graph span()代码>?甚至只是说Graph::Graph span代码>?