我有一个包含 Car 类实例的 Tran 类。如果程序在 typedef
之前包含 typename
,则会产生错误:“expected nested-name-specifier before typedef
”。如果它不包含 typename
,它会产生一个错误:“在 'Tran::CarType::Model' 之前需要 'typename' 因为 'Tran::CarType' 是一个依赖范围”。是什么导致了这个问题?
#include "Car.hpp"
template<typename A, typename B, typename C>
class Tran {
public:
typedef Car<A, B> CarType; //compilation error
typedef CarType::Model M; //compilation error
private:
CarType myCar;
}
最佳答案
问题出在这一行:
typedef CarType::Model M;
这里,注意 CarType
定义为
typedef Car<A, B> CarType;
请注意 CarType
取决于 A
和 B
是什么。事实上,正因如此,它才被称为依赖类型。
在 C++ 中,如果要访问嵌套在依赖类型内部的类型,则必须明确告诉编译器您正在依赖类型内部查找其他类型的名称。因此,这一行是错误的:
typedef CarType::Model M;
因为没有迹象表明 Model
是类型名称。要解决此问题,请将行更改为 read
typedef typename CarType::Model M;
这里,typename
关键字向 C++ 指示 Model
是嵌套在依赖类型 CarType
中的类型的名称。
希望这对您有所帮助!
关于c++ - 在 C++ 中产生 typename 和 typedef 相关错误的模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16050550/