如何从通过模板继承的类中提取 typedef'd 信息?

How can you extract typedef'd information from a class that is inherited through templates?

本文关键字:typedef 提取 信息 继承      更新时间:2023-10-16

我有一个关于从通过模板继承的类中提取typedef'd信息的问题。为了说明我的问题,请考虑以下简单示例:

#include <iostream>
class A1{
public:
    void print(){ printf("I am A1n"); };
};
class A2{
public:
    void print(){ printf("I am A2n"); };
};
class B1{
public:
    typedef A1 A;
};
class B2{
public:
    typedef A2 A;
};
template<class b>
class C{
    typedef class b::A AA;
    AA a;
public:
    void Cprint() {     a.print();  };
};
int main()
{
    C<B1> c1;
    c1.Cprint();
    C<B2> c2;
    c2.Cprint();
}

类 C 将类(B1 或 B2)作为模板参数。B1 和 B2 都有一个名为 A(分别为 A1 和 A2 类)的 tyepdef。在编译时,类 C 应该能够找出"B"类正在使用两个"A"类中的哪一个。当我使用 g++ 编译时,上面的代码可以完美运行。但是,当我使用英特尔的 icpc 编译它时,出现以下错误:

test.cpp(24): error: typedef "A" may not be used in an elaborated type specifier
    typedef class b::A AA;
                     ^
    detected during instantiation of class "C<b> [with b=B1]" at line 33

有没有其他方法可以达到类似的效果?当然,我的实际代码要复杂得多,我希望以这种方式构建类是有原因的。我想用 icpc 而不是 g++ 编译也是有原因的。

提前谢谢。卡尔

尝试更改:

template<class b>
class C{
    typedef class b::A AA;
    AA a;
public:
    void Cprint() {     a.print();  };
};

自:

template<class b>
class C{
    typedef typename b::A AA;
    AA a;
public:
    void Cprint() {     a.print();  };
};

b::A 是依赖类型(它取决于用于b的类型)。

仅供参考,原始发布的代码无法使用VS2008和VS2010进行编译。