C++ 错误:“依赖名称不是类型”。当在类中使用 typedef 类型作为返回值时,使用模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16131838/
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-27 20:05:39  来源:igfitidea点击:

ERROR: "dependent name is not a type". When use typedef type in class as return value, with template

c++

提问by Yuan Wang

template <class Item>
class bag
{
public:
    //TYPEDEF
    typedef size_t size_type;
    typedef Item value_type;
...
}

and when I use

当我使用

template<class Item>
bag<Item>::size_type bag<Item>::count(const Item& target) const

VC++ report error as Source.cpp(207): warning C4346: 'bag::size_type' : dependent name is not a type

VC++ 报告错误为 Source.cpp(207): warning C4346: 'bag::size_type' :dependent name is not a type

Could anybody show me why? Thanks!

有人能告诉我为什么吗?谢谢!

回答by Vaughn Cato

It should be

它应该是

template<class Item>
typename bag<Item>::size_type bag<Item>::count(const Item& target) const

回答by 0x499602D2

You need to prepend typenamebefore bag<Item>::size_typeas it is a dependent type.

您需要在前面加上typenamebag<Item>::size_type因为它是一个依赖类型

typename bag<Item>::size_type bag<Item>::count(const Item& target) const

As per the C++11 Standard:

根据 C++11 标准:

14.6 Name resolution

A name used in a template declaration or de?nition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup ?nds a type name or the name is quali?ed by the keyword typename.

14.6 名称解析

在模板声明或定义中使用且依赖于模板参数的名称被假定为不命名类型,除非适用的名称查找找到类型名称或名称由关键字限定typename

Related: Where and why do I have to put the "template" and "typename" keywords?

相关:我必须在哪里以及为什么要放置“模板”和“类型名称”关键字?