为什么派生类找不到基类的类型别名? [英] Why can't my derived class find my base class's type alias?
问题描述
让我们从代码示例开始,因为应该很容易看到正在发生的事情:
Let's start with the code example, because it should be easy to see what's going on:
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()
{}
预期派生找到基本类型别名。但是,我尝试过的所有编译器(MSVC,Clang和GCC)似乎都不喜欢此代码。
I would have expected Derived to find Base's Type alias. However, none of the compilers I've tried (MSVC, Clang, GCC) seem to like this code.
更令人惊讶的是,将Derived的继承更改为:
More surprisingly, changing Derived's inheritance to:
struct Derived : public Base<int>
解决了这个问题。
是否存在我可以更改某些内容以允许派生找到Base的别名吗?
Is there something I can change to allow Derived to find Base's alias?
推荐答案
因为 Type
是从属名称(取决于模板 Base< T>
)。您需要限定它并使用 typename
。您还可以使用 Derived ::
(如 op 自己找出来):
because Type
is a dependent name (it depends on the template Base<T>
). You need to qualify it and use typename
. You can also qualify it with Derived::
(as the op himself figure it out):
template<typename T>
struct Derived : public Base<T>
{
using NewType = typename Base<T>::Type;
// or
using NewType2 = typename Derived::Type;
};
您可以在此处详细了解相关名称:
You can read more about dependent names here:
https://en.cppreference.com/w/cpp/language/dependent_name
Why do I have to access template base class members through the this pointer?
这篇关于为什么派生类找不到基类的类型别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!