【问题标题】:In a C++ template, is it allowed to return an object with specific type parameters?在 C++ 模板中,是否允许返回具有特定类型参数的对象?
【发布时间】:2011-01-30 16:17:29
【问题描述】:

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

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

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

【问题讨论】:

  • 为什么?如果您要强制其他所有内容都成为int,为什么不放弃中间模板参数并完成它?
  • @potatoswatter:它编译得很好,我还没有达到可以运行整个程序的地步。 @gman:只有这个函数我希望它是int,在Graph 的其余部分中它可能是其他任何东西。还是我误会了你?

标签: c++ templates


【解决方案1】:

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

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

【讨论】:

  • @agnel-kurian 是否可以按值返回 Graph 的副本?还是我必须始终使用带有new 关键字的指针?
  • 您必须使用带有new 关键字的指针。退回副本没问题。
  • @agnel 返回本地指针是个坏主意。我认为最好还是返回一个副本,但是像这样创建新图: Graph span = Graph::Graph();
  • @agnel-kurian:所以如果我使用 new,我必须按照您的建议进行操作?
  • @draco-ater:这相当于说Graph&lt;edgeDecor,int,dir&gt;::Graph&lt;edgeDecor,int,dir&gt; span(); 吗?或者只是说Graph&lt;edgeDecor,int,dir&gt;::Graph&lt;edgeDecor,int,dir&gt; span;
【解决方案2】:

事实上,你可以返回任何你想要的东西。您甚至可以返回取决于模板参数的内容:

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】:

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

    【讨论】:

      猜你喜欢
      • 2013-09-15
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多