Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 'using' and 'using typename' in a header file

Tags:

c++

header

using

In the C++ code below, could somebody explain what each of these lines mean in the private section? I have tried looking it up, but I still cannot figure out what they do.

I understand that using is the equivalent to typedef in C. So:

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

Means that you use the_graph.

But, in this instance, why would you call the scope resolution operator on it?

I don't think that it is any of the 4 methods described here.

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;
};
like image 733
ariane cathal Avatar asked Oct 20 '25 01:10

ariane cathal


2 Answers

The using directive is used to bring a name into the current scope that otherwise is not.

Example:

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.
}

When a name is dependent upon a template parameter, the standard requires that you use the elaborate form

using typename the_graph::node_list_iterator;

After that line, you can use node_list_iterator as a typename.

Had the_graph not been a class template, you could have used the simpler form

using the_graph::node_list_iterator;

Further reading: Where and why do I have to put the "template" and "typename" keywords?

like image 170
R Sahu Avatar answered Oct 21 '25 14:10

R Sahu


Those using make visible the associated name and avoid ambiguity.

Both bases should have type node_list_iterator and method(s) node_begin.

like image 28
Jarod42 Avatar answered Oct 21 '25 15:10

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!