Search code examples
c++templatesc++11using

C++ `using` command for type alias in template class


This seems like it should be really simple, but I've been playing and havn't found the solution I'm looking for yet, so here goes:

I have the following struct (simplified for illustrative purposes of course):

template<typename T>
struct test
    {
    using L = std::list<T>;
    L::iterator a;
    };

Now, this throws the error:

error: need 'typename' before 'test<T>::K::iterator' because 'test<T>::K' is a dependent scope

The two ways I have found of fixing it so far are both less than ideal:

1) add typename before any use of L:

template<typename T>
struct test
    {
    using L = std::list<T>;
    typename L::iterator a;
    };

I'd rather avoid the extra verbosity of this if possible.

2) add another using statement to target the iterator directly:

template<typename T>
struct test
    {
    using L = std::list<T>;
    using iter = typename L::iterator;
    iter a;
    };

But that would require having to do the same for every iterator I wanted to use, if I also wished to access the const_iterator etc etc, and I'd rather not have to define a bunch of using statements.

So, is there a way to write the using statement that then allows me to write:

 L::iterator a;
 L::const_iterator b;
 ...

Thanks!


Solution

  • The typename must be there, but you can use a couple of alias template utilities to avoid defining a new iter type every time:

    template<typename C>
    using Iterator = typename C::iterator;
    
    template<typename C>
    using ConstIterator = typename C::const_iterator;
    
    template<typename T>
    struct test
    {
        using L = std::list<T>;
        Iterator<L> i;
        ConstIterator<L> ci;
    };