【问题标题】:A template class that produces typename and typedef related errors in C++?在 C++ 中产生 typename 和 typedef 相关错误的模板类?
【发布时间】:2013-04-17 02:44:35
【问题描述】:

我有一个包含 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;
}

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    问题在于这一行:

    typedef CarType::Model M;
    

    这里注意CarType被定义为

    typedef Car<A, B> CarType;
    

    请注意,CarType 取决于 AB 是什么。事实上,它被称为依赖类型

    在 C++ 中,如果您想访问嵌套在依赖类型中的类型,您必须明确告诉编译器您正在从依赖类型内部查找其他类型的名称。因此,这一行是错误的:

    typedef CarType::Model M;
    

    因为没有迹象表明Model 是一个类型名称。要解决此问题,请将行更改为读取

    typedef typename CarType::Model M;
    

    这里,typename 关键字向 C++ 表明 Model 是嵌套在依赖类型 CarType 内的类型的名称。

    希望这会有所帮助!

    【讨论】:

    • 我应该猜到这个问题是你的... template typedef :)
    • @DavidRodríguez-dribeas- 我在打字时就这么想。 :-)
    【解决方案2】:

    正确的顺序是typedef typename,而不是相反。您只需要在第二个声明中使用它,因为它是一个依赖名称,编译器在查找的第一阶段无法知道 CarType::Model 是什么。

    【讨论】:

      猜你喜欢
      • 2011-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2013-04-14
      • 1970-01-01
      相关资源
      最近更新 更多