开发者

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?


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;
};


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&) { /** **/ };


Its certainly possible. To me the above code appears valid

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜