类成员的类型定义

typedef for class member

本文关键字:定义 类型 成员      更新时间:2023-10-16

是否可以用类成员/函数做一个typedef?在下面的示例中,我使用 boost bimap 函数来存储有关节点最近邻居的信息。

typedef boost::bimap<float /*distance*/, int /*id*/> neighbor_list;
neighbor_list node_a;
//fill up neighbors of node_a
//get nearest neighbor of node_a
node_a.neighbor.left.begin()->second;
//get distance to the nearest neighbor of node_a
node_a.neighbor.left.begin()->first;

然而,上面的线条看起来很混乱,可能不直观。所以我想知道是否可以为班级成员做一个typedef,这样我就可以做如下事情

typedef boost::bimap<float /*distance*/, int /*id*/> neighbor_list;
typedef neighbor_list::left::begin()->first nearest_neighbor;
//nearest neighbor of node_a
node_a.nearest_neighbor;

我知道我可以编写自己的函数来封装代码的混乱部分,但我想知道我是否可以为类成员提供别名。

只需将讨厌的分辨率委托给函数即可。

#include <boost/bimap.hpp>
typedef boost::bimap<float /*distance*/, int /*id*/> neighbor_list;
float nearest_neighbor(neighbor_list const& node)
{
  return node.neighbor.left.begin()->first;
}
void foo()
{
  neighbor_list node_a;
  nearest_neighbor(node_a);
}