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?
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.
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.
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.
The following will work:
typename Test1<T>::t1 x;
and, as Xeo points out in the comments above, so does:
typename Test2::t1 x;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With