C++ 具有依赖范围的嵌套模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3311633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:36:20  来源:igfitidea点击:

Nested templates with dependent scope

c++templatesscopenested

提问by user383352

What is dependent scope and what is the meaning of typename in the context of the following error?

在以下错误的上下文中,什么是依赖范围以及 typename 的含义是什么?

$ make
g++ -std=gnu++0x main.cpp
main.cpp:18:10: error: need 'typename' before 'ptrModel<std::vector<Data> >::Type' because 'ptrModel<std::vector<Data> >' is a dependent scope
make: *** [all] Error 1


/*
 * main.cpp
 */

#include <vector>
#include <memory>

template<typename T>
struct ptrModel
{
 typedef std::unique_ptr<T> Type;
};


template<typename Data>
struct ptrType
{
 typedef ptrModel< std::vector<Data> >::Type Type;
};

int main()
{
 return 0;
}

回答by Tyler McHenry

The compiler told you exactly what to do. Write typenamebefore ptrModel<std::vector<Data> >::Type, like so:

编译器会准确地告诉您要做什么。写typename之前ptrModel<std::vector<Data> >::Type,像这样:

 typedef typename ptrModel<std::vector<Data> >::Type Type;

The reasonfor this requirement is that the compiler doesn't at this point know whether ptrModel<std::vector<Data> >::Typedescribes a member variable or a nested type. It can't even figure that out by looking at the definition of ptrModelbecause there might be a specialization of ptrModelfor std::vector<Data>somewhere else in the program that it hasn't gotten to yet which changes which of these things ::Typerefers to. So you need to tell it explicitly.

这个要求的原因是编译器此时不知道是ptrModel<std::vector<Data> >::Type描述成员变量还是嵌套类型。它甚至无法通过查看 的定义来弄清楚,ptrModel因为可能在程序中的其他地方有一个专门化的ptrModelforstd::vector<Data>尚未到达哪些更改这些事物中的哪一个::Type。所以你需要明确地告诉它。

The name ptrModel<std::vector<Data> >::Typehas a "dependent scope" because it is in a scope that dependson the instantiation of a template.

该名称ptrModel<std::vector<Data> >::Type具有“依赖范围”,因为它位于依赖于模板实例化的范围内。