简体   繁体   English

在C ++中会产生与typename和typedef相关的错误的模板类?

[英]A template class that produces typename and typedef related errors in C++?

I have a class Tran that contains an instance of a class Car. 我有一个Tran类,其中包含Car类的实例。 If the program includes typename before typedef , it produces an error: "expected nested-name-specifier before typedef ". 如果程序在typedef之前包含typename ,则会产生错误:“ typedef之前的嵌套名称说明符”。 If it does not include typename , it produces an error: "need 'typename' before 'Tran::CarType::Model' because 'Tran::CarType' is a dependent scope". 如果不包含typename ,则会产生错误:“在'Tran :: CarType :: Model'之前需要'typename',因为'Tran :: CarType'是从属范围”。 What is causing this problem? 是什么导致此问题?

#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;
}

The issue is with this line: 问题在于此行:

typedef CarType::Model M;

Here, note that CarType is defined as 在这里,请注意CarType被定义为

typedef Car<A, B> CarType;

Notice that CarType depends on what A and B are. 请注意, CarType取决于AB是什么。 In fact, it's called a dependent type because of this. 实际上,因为这个原因,它称为依赖类型

In C++, if you want to access a type nested inside of a dependent type, you have to explicitly tell the compiler that you are looking inside of a dependent type for the name of some other type. 在C ++中,如果要访问嵌套在依赖类型内部的类型,则必须明确告知编译器您正在依赖类型内部查找其他类型的名称。 Therefore, this line is an error: 因此,此行是一个错误:

typedef CarType::Model M;

Because there is no indication that Model is a type name. 因为没有迹象表明Model是类型名称。 To fix this, change the line to read 要解决此问题,请将行更改为

typedef typename CarType::Model M;

Here, the typename keyword indicates to C++ that Model is the name of a type nested inside the dependent type CarType . 在这里, typename关键字向C ++指示Model是嵌套在从属类型CarType内的类型的名称。

Hope this helps! 希望这可以帮助!

The correct order is typedef typename and not the other way around. 正确的顺序是typedef typename而不是相反。 You only need it in the second declaration, as it is a dependent name and the compiler cannot know during the first phase of lookup what CarType::Model is. 您只需要在第二个声明中使用它,因为它是一个从属名称,并且编译器在查找的第一阶段无法知道什么是CarType::Model

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM