Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using declaration for type alias template in derived class with tempate base

If the base class depends on the template parameter, its scope is not examined in the unqualified name lookup. I can use the using declaration to introduce names from the base class. Suppose now I have a type alias template in the base class. Can the using declaration be used to introduce it into the derived class?

template<class T>
struct Base
{
    using Type1 = int;

    template<typename S>
    using Type2 = S;
};

template<class T>
struct Derived : Base<T>
{
    using typename Base<T>::Type1;           // Fine
    //using Type1 = typename Base<T>::Type1; // Also fine

    template<typename S>
    using Type2 = typename Base<T>::template Type2<S>;
};

Can the line for Type2 be replaced with something similar to the (uncommented) line for Type1?

like image 550
Evg Avatar asked Mar 02 '26 06:03

Evg


1 Answers

template<class T>
struct Derived : Base<T>
{
    using Base<T>::Type2;

    void foo() {
        // Using the Type2 alias template
        // inside our class to declare a local variable.
        typename Derived::template Type2<int> i;
    }
};

// Using the Type2 alias template
// outside the class to declare another type.
using X = Derived<int>::Type2<int>;

This is the correct syntax, and all compilers that support C++11 should allow this. See here for a live demo.

what I meant is something simple like this: using Base<T>::Type2;, possibly with typenames and templates.

We don't need these disambiguators in the using declaration, but when we want to use Type2 in Derived, we still need:

  • the template disambiguator because Type2 is a template and Derived is dependent on T
  • the typename disambiguator to specify that Type2<...> is a type

See also: cppreference article on dependent names

like image 89
Jan Schultke Avatar answered Mar 03 '26 20:03

Jan Schultke



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!