c++ - 在类中使用模板参数中的类型名
问题描述
//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对不起,不清楚问题名称,但我无法发明更好的问题。
解决方案
当您定义class B : public A<B>
类B
未定义但您尝试在 A 中使用此类时。此时,编译器不知道是否会有using Type = int;
.
gcc 提供了更易读的错误消息:“invalid use of incomplete type 'class B'”
void A<T>::f()
永远不会被实例化,因此您不会看到错误消息。
坏消息:在这种情况下你没有机会做任何类型的前向声明,因为你有一个完整的循环依赖。
推荐阅读
- python - 绘制按变量分组的多个 seaborn kde
- rust - 当依赖项采用简单格式时,为什么我会收到“错误:无效通道名称'[toolchain]'”?
- php - Magento 2 | getImage() 函数在自定义 phtml 文件中不起作用
- json - 如何在 .NET 5 API 中创建自定义 JSON 序列化器/反序列化器
- javascript - 使用 Sapper 预加载来获取图像
- javascript - 有 n 个状态在反应,假设 n 不会在道具中收到
- javascript - 创建一个接受输入值并根据用户值的值添加文本框的网页
- c# - 如何将原始 json 包含到反序列化对象中?
- twilio - 有没有办法以编程方式响应 Twilio 工作室的执行?
- python - 将json的输出存储在变量中时出现KeyError