Niel de Wet
Niel de Wet

Reputation: 8398

In a C++ template, is it allowed to return an object with specific type parameters?

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

Answers (3)

Matthieu M.
Matthieu M.

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

Agnel Kurian
Agnel Kurian

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

mukeshkumar
mukeshkumar

Reputation: 2778

Its certainly possible. To me the above code appears valid

Upvotes: 0

Related Questions