Skip to main content
 首页 » 编程设计

c++之为什么类不能继承其父类的成员类型

2024年05月22日36bjzhanghao

template<typename T> 
struct A 
{ 
    using U = int; 
}; 
 
struct B : A<int> 
{ 
    void f(U) // ok 
    {} 
}; 
 
template<typename T> 
struct C : A<int> 
{ 
    void f(U) // ok 
    {} 
}; 
 
template<typename T> 
struct D : A<T> 
{ 
    void f(U) // fatal error: unknown type name 'U' 
    {} 
}; 
 
int main() 
{ 
    B      b; // ok 
    C<int> c; // ok 
    D<int> d; // error 
} 

为什么类不能继承其父类的成员类型?

请您参考如下方法:

成员(member)U像任何其他成员一样继承,无论哪些类是模板化的,但根据 C++17 [temp.dep]/3,通过非限定名称查找找不到它:

In the definition of a class or class template, the scope of a dependent base class (17.6.2.1) is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

在这里,A<T>是一个依赖基类,因为它依赖于模板参数 T类模板的D .

强制编译器查找U在基类中,您必须使用限定名称查找。你可以这样做:

void f(typename A<T>::U); 

如果基类的模板参数很复杂,另一种表达方式是:

void f(typename D::A::U); 

如果您要多次写入此内容,那么您也可以在 D 中重新声明类型。为了方便起见:

using U = typename A<T>::U; 
void f(U); 

注意:在上述情况下,typename在 C++20 中将成为可选。