如何从派生的模板类访问基类中定义的模板类型?[复制]

How to access a template type defined in base class from a derived template class? [duplicate]

提问人:czs108 提问时间:3/21/2023 更新时间:3/21/2023 访问量:45

问:

这是我的代码:

// Here can be more types of base classes and they all define `InsideType`.
struct BaseClass
{
    template <class T>
    struct InsideType
    {
    };
};

// The subclass can inherit from one type of base class. 
template <class Base>
struct SubClass : public Base
{
    // Compile-Error on Visual Studio 2022 C++20:
    //   error C2059: syntax error: '<'
    //   error C2238: unexpected token(s) preceding ';'
    typename Base::InsideType<int> val;
};

int main()
{
    SubClass<BaseClass> var;
    return 0;
}

我想从派生的模板类访问。但似乎只在不是模板类型时才有效。InsideTypeSubClasstypenameInsideType

编译错误在 Visual Studio 2022 C++20 上没有意义:

// error C2059: syntax error: '<'
// error C2238: unexpected token(s) preceding ';'
typename Base::InsideType<int> val;

有什么办法可以做到这一点吗?谢谢。

C++ 模板 继承 类型名称

评论

1赞 Drew Dormann 3/21/2023
您要键入 .Base::template InsideType
0赞 czs108 3/21/2023
@DrewDormann,非常感谢,我根据您的回答找到了它的详细信息: en.cppreference.com/w/cpp/language/dependent_name依赖名称的模板消歧器

答:

1赞 Vlad from Moscow 3/21/2023 #1

请尝试以下操作

template <class Base>
struct SubClass : public Base
{
    // Compile-Error on Visual Studio 2022 C++20:
    //   error C2059: syntax error: '<'
    //   error C2238: unexpected token(s) preceding ';'
    typename Base:: template InsideType<int> val;
};

评论

0赞 Vlad from Moscow 3/21/2023
@czs108完全没有。不客气:)