让我们从代码示例开始,因为应该很容易看到正在发生的事情:
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>
解决了这个问题。
我可以更改某些内容以允许“派生”找到Base的别名吗?
答案 0 :(得分:5)
因为Type
是一个从属名称(它取决于模板Base<T>
)。您需要限定它并使用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