Search code examples
c++headerusing

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


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

Solution

  • 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?