Reputation: 8398
When I've got a template with certain type parameters, is it allowed for a function to return an object of this same template, but with different types? In other words, is the following allowed?
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;
};
If this is not allowed, how can I accomplish the same kind of thing?
Upvotes: 3
Views: 3324
Reputation: 299930
In fact, you can return whatever you want. You can even return something that depends on the template parameters:
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&) { /** **/ };
Upvotes: 1
Reputation: 59466
Allowed. Some corrections to your code sample:
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;
};
Upvotes: 2