繁体   English   中英

头文件中的C ++“使用”和“使用类型名”

[英]C++ 'using' and 'using typename' in a header file

在下面的C ++代码中,有人可以解释这些部分中的每行在private部分中的含义吗? 我曾尝试查找它,但仍然无法弄清它们的作用。

我了解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;
};

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”关键字?

那些using使人们看到了相关的名称,避免歧义。

这两个库都应具有类型node_list_iterator和方法node_begin

在模板的定义和声明中,关键字typename用于指定合格ID(即some_name::some_member )是类型而不是变量。 在模板实例化之前,此关键字是必需的,因为编译器不知道some_name的定义,并且如果没有typename ,它将假定some_member是变量(或函数)。

然后,使用using typename::node_list_iterator的using指令可从graph类私有访问node_list_iterator

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM