C++头文件中的'using'和'using typename'

3
在下面的C++代码中,有人能解释一下私有部分每行是什么意思吗?我已经尝试过查找,但仍然无法理解它们的作用。
我知道using在C中等同于typedef。因此:
using the_graph = graph<T_node, T_edge1, T_allocator, T_size>;

这意味着你正在使用the_graph

但在这种情况下,为什么要在其上调用作用域解析运算符呢?

我认为它不是这里描述的 4 种方法之一。

template <class T_node, class T_edge1, class T_edge2, class T_allocator, class T_size = uint32_t>
class graph : private virtual graph<T_node, T_edge1, T_allocator, T_size>, private virtual graph<T_node, T_edge2, T_allocator, T_size>
{

public:

    using the_graph = graph<T_node, T_edge1, T_allocator, T_size>;


private:

    using typename the_graph::node_list_iterator;
    using the_graph::node_begin;
};

3个回答

8
using指令用于将一个在当前作用域之外的名称引入到当前作用域中。
例如:
struct Foo
{
    struct Bar {};
};

int main()
{
   Bar b1; // Not ok. Bar is not in scope yet.

   using Foo::Bar;
   Bar b2; // Ok. Bar is now in scope.
}

当名称依赖于模板参数时,标准要求您使用全名形式

using typename the_graph::node_list_iterator;

在那行代码之后,你可以使用node_list_iterator作为类型名称。
如果the_graph不是一个类模板,你可以使用更简单的形式。
using the_graph::node_list_iterator;

进一步阅读:在哪里和为什么我必须使用“template”和“typename”关键字?

1

使用using可以使关联名称可见并避免歧义。

两个基类应该具有类型node_list_iterator和方法node_begin


1
在模板的定义和声明中,关键字 typename 用于指定限定标识符(即 some_name::some_member)是类型而不是变量。在模板实例化之前,这个关键字是必需的,因为编译器不知道 some_name 的定义,并且如果没有 typename,它会认为 some_member 是一个变量(或函数)。
然后使用指令 using typename::node_list_iterator 使得从 graph 类可以私有地访问 node_list_iterator

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接