代码之家  ›  专栏  ›  技术社区  ›  Niel de Wet

在C++模板中,是否允许返回具有特定类型参数的对象?

  •  3
  • Niel de Wet  · 技术社区  · 15 年前

    当我有一个带有特定类型参数的模板时,是否允许函数返回具有相同模板但具有不同类型的对象?换句话说,是否允许以下内容?

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

    如果不允许这样做,我怎样才能完成同样的事情?

    3 回复  |  直到 15 年前
        1
  •  2
  •   Agnel Kurian    15 年前

    允许。代码示例的一些更正:

    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;
    };
    
        2
  •  1
  •   Matthieu M.    15 年前

    事实上,你可以随心所欲地退货。甚至可以返回依赖于模板参数的内容:

    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&) { /** **/ };
    
        3
  •  0
  •   mukeshkumar    15 年前

    当然有可能。对我来说,上述代码似乎有效