【问题标题】:Get templated, template type获取模板,模板类型
【发布时间】:2012-11-08 15:39:07
【问题描述】:

我正在创建一个小的“通用”寻路类,它采用 Board 的类类型,它将在其上查找路径,

//T - Board class type
template<class T>
class PathFinder
{...}

Board 也被模板化以保存节点类型。 (这样我就可以在 2D 或 3D 向量空间上找到路径)。

我希望能够为PathFinder 声明和定义一个成员函数,它将接受像这样的参数

//T - Board class type
PathFinder<T>::getPath( nodeType from, nodeType to);

如何对作为参数输入函数的TnodeType 的节点类型执行类型兼容性?

【问题讨论】:

  • nodeType和T一样吗?

标签: c++ class templates types


【解决方案1】:

如果我明白你想要什么,请给 board 一个类型成员并使用它:

template<class nodeType>
class board {
  public:
    typedef nodeType node_type;
  // ...
};

PathFinder<T>::getPath(typename T::node_type from, typename T::node_type to);

如果不能更改board,也可以进行模式匹配:

template<class Board>
struct get_node_type;
template<class T>
struct get_node_type<board<T> > {
  typedef T type;
};

PathFinder<T>::getPath(typename get_node_type<T>::type from, typename get_node_type<T>::type to);

【讨论】:

  • 这是干什么用的? template&lt;class Board&gt; struct get_node_type;
  • @KarthikT 没有它你就不能部分专业化。
【解决方案2】:

你可以在类定义中typedefnodeType

typedef typename T::nodeType TNode;
PathFinder<T>::getPath( TNode from, TNode to);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多