Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inheritance of type aliases within templates

It looks like I an inherit type aliases among classes, but not among class templates? I don't understand why this code works:

#include <iostream>

//template<typename T>
struct Test1
{
//    using t1=T;
    using t1=int;
};

//template<typename T>
struct Test2: public Test1//<T>
{
  t1 x;  
};

int main(int argc, char *argv[]) {
//    Test2<int> a;
    Test2 a;
    a.x=5;
    std::cout << a.x << std::endl;
}

and this code does not:

#include <iostream>

template<typename T>
struct Test1
{
    using t1=T;
};

template<typename T>
struct Test2: public Test1<T>
{
  t1 x;  
};

int main(int argc, char *argv[]) {
    Test2<int> a;
    a.x=5;
    std::cout << a.x << std::endl;
}

Do types not inherit through templates?

like image 496
Omegaman Avatar asked Jul 28 '13 21:07

Omegaman


People also ask

What is template type alias?

Type alias is a name that refers to a previously defined type (similar to typedef). Alias template is a name that refers to a family of types.

Can template class inherit?

Inheriting from a template classIt is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.

What is an alias in C++?

You can use an alias declaration to declare a name to use as a synonym for a previously declared type. (This mechanism is also referred to informally as a type alias). You can also use this mechanism to create an alias template, which can be useful for custom allocators.


1 Answers

The following will work:

 typename Test1<T>::t1 x;

and, as Xeo points out in the comments above, so does:

typename Test2::t1 x;
like image 183
sgun Avatar answered Sep 30 '22 09:09

sgun