簡體   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