首页 > 解决方案 > 在类中使用模板参数中的类型名

问题描述

//A.h
template <class T>
class A
{
public:
    typename T::Type x; //(1) compile time error: C2039 'Type': is not a member of 'B'
    void f();
};
template <class T>
void A<T>::f() 
{ 
  typename T::Type x1; //(2) but no errors here
}

//B.h 
#include "A.h"

class B : public A<B>
{
public:
    using Type = int;
};

//main.cpp
#include "B.h"

int main()
{
    B x;
}

为什么(1)有错误,而(2)没有错误?如何存储类型变量并像A 类typename T::Type一样编写函数?func(typename T::Type)

我不知道为什么要完成这个类的设计,也不想更改代码中的类层次结构或模板参数,因为有很多类继承自 A 并且代码非常混乱。所以请不要以这种方式提出建议。

PS对不起,不清楚问题名称,但我无法发明更好的问题。

标签: c++

解决方案


当您定义class B : public A<B>B未定义但您尝试在 A 中使用此类时。此时,编译器不知道是否会有using Type = int;.

gcc 提供了更易读的错误消息:“invalid use of incomplete type 'class B'”

void A<T>::f()永远不会被实例化,因此您不会看到错误消息。

坏消息:在这种情况下你没有机会做任何类型的前向声明,因为你有一个完整的循环依赖。


推荐阅读