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

标签 c++ oop templates inheritance standards

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 中将成为可选。

关于c++ - 为什么类不能继承其父类的成员类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61515019/

相关文章:

推断使用的变量和依赖项的 Javascript 模板库

c++ - 打开 .dat 文件时遇到问题

c++ - 为什么这个程序不能在VC++2008Express中编译?

c++ - myVector.erase(myPtr) 是否删除 myPtr 指向的对象?

python - 为什么内置函数而不是根类方法?

C++:无法为 Vertex 对象创建哈希函数

python - 传递列表并将其长度设置为python中的默认参数

c++ - BOOST_PHOENIX_ADAPT_FUNCTION(...) 在模板化容器上使用模板化函数

c++ - 如何在 `operator==` 包装类中使用重载 `std::variant` 来比较 Setting Vs Setting 和 T vs T?

c++ - 如何将具有双高/双宽字符的字符串转换为普通字符串[VC++6]