【问题标题】:typedef for class member类成员的 typedef
【发布时间】:2017-06-21 04:56:08
【问题描述】:

是否可以对类成员/函数进行 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;

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

【问题讨论】:

  • typedef 用于类型(真是令人惊讶)。函数不是类型。
  • 但是您可以将您的预期行为包装在另一个函数中。这将允许您输入nearest_neighbor(node_a)
  • 嗨,是的,我知道这一点。我还没有深入研究 C++,所以我想知道是否有一种方法可以满足我的要求
  • @Henri Menke 谢谢我猜函数是最简单的解决方案

标签: c++ boost typedef


【解决方案1】:

只需将讨厌的解决方案委托给一个函数。

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

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 2012-11-04
    • 2021-10-08
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多