【问题标题】:Why can't my derived class find my base class's type alias?为什么我的派生类找不到我的基类的类型别名?
【发布时间】:2019-08-03 00:50:11
【问题描述】:

让我们从代码示例开始,因为它应该很容易看出发生了什么:

template <typename T>
struct Base
{
    using Type = int;
};

template<typename T>
struct Derived : public Base<T>
{
    // error: unknown type name 'Type'
    using NewType = Type;
};

int main()
{}

我原以为 Derived 会找到 Base 的 Type 别名。但是,我尝试过的所有编译器(MSVC、Clang、GCC)似乎都不喜欢这段代码。

更令人惊讶的是,将 Derived 的继承改为:

struct Derived : public Base<int>

解决问题。

我可以更改什么以允许 Derived 找到 Base 的别名吗?

【问题讨论】:

  • 另外,这是我在 Stack Overflow 上的第一个问题,如果有什么可以改进的,请告诉我!
  • 用完美的minimal reproducible example很好地完成了一个清晰的问题陈述

标签: c++ c++11


【解决方案1】:

因为Type 是一个从属名称(它依赖于模板Base&lt;T&gt;)。您需要对其进行限定并使用typename。你也可以用Derived:: 来限定它(op 自己想出来):

template<typename T>
struct Derived : public Base<T>
{
    using NewType = typename Base<T>::Type;
    // or
    using NewType2 = typename Derived::Type;
};

您可以在此处阅读有关从属名称的更多信息:

https://en.cppreference.com/w/cpp/language/dependent_name

How do you understand dependent names in C++

Where and why do I have to put the "template" and "typename" keywords?

Why do I have to access template base class members through the this pointer?

"not declared in this scope" error with templates and inheritance

【讨论】:

  • 感谢您的回答;缺少上下文对于为什么它无法弄清楚 Type 是有道理的——据它所知;基类将专门用于拥有完全不同的东西。不过,您的解决方案依赖于我们知道 Type 的来源。查看您的最后一个链接让我想到了使用using NewType = typename Derived::Type;,这使多重继承等变得更容易。您介意将其添加到您的解决方案中吗?这会对我的情况有很大帮助。
  • @JoshuaMaiche 完全正确。也是的,我同意Derived::Type; 更好。好收获
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 2017-01-13
  • 1970-01-01
  • 2016-02-14
  • 2019-09-02
  • 1970-01-01
相关资源
最近更新 更多