C++ 模板方法编译错误,返回是内部类的实例

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

Compiling error on template method, return is instance from inner class

c++templates

提问by lampyridae

Here is a simplified example:

这是一个简化的示例:

template<typename T>
class MyTemplate
{
  class Inner {};
  Inner met();
};

template<typename T>
MyTemplate<T>::Inner  MyTemplate<T>::met()
{ }

I get the following compilation error:

我收到以下编译错误:

expected constructor, destructor, or type conversion before 'met'

I use GCC. It seems the compiler doesn't recognize MyTemplate<T>::Inneras a proper class. How can I fix this? I've tried sticking the typenamekeyword here and there to no avail. Right now, the only way I can manage to compile this is to inline the method definition in the class declaration, which I would like to avoid.

我使用海湾合作委员会。编译器似乎无法识别MyTemplate<T>::Inner为正确的类。我怎样才能解决这个问题?我试过在typename这里和那里粘贴关键字无济于事。现在,我可以设法编译它的唯一方法是在类声明中内联方法定义,我想避免这种情况。

回答by Michael Price

Clang reports the following:

Clang 报告以下内容:

error: missing 'typename' prior to dependent type name
'MyTemplate<T>::Inner' MyTemplate<T>::Inner  MyTemplate<T>::met()
^~~~~~~~~~~~~~~~~~~~ typename  1 error generated.

And placing typenamein the appropriate place fixes it.

并放置typename在适当的位置修复它。

template<typename T>
class MyTemplate
{
  class Inner {};
  Inner met();
};

template<typename T>
typename MyTemplate<T>::Inner  MyTemplate<T>::met()
{ }

Did you put typename in the correct location? If so, then this must be a bug in G++.

你把 typename 放在正确的位置了吗?如果是这样,那么这一定是 G++ 中的错误。

回答by Praetorian

The return type of MyTemplate::metis a dependent name, so you need to add the typenamekeyword before it. The following compiles on gcc-4.5.1

的返回类型MyTemplate::met是一个依赖名称,所以需要typename在它前面加上关键字。以下在 gcc-4.5.1 上编译

template<typename T>
struct MyTemplate
{
  class Inner {};
  Inner met();
};

template<typename T>
typename MyTemplate<T>::Inner  MyTemplate<T>::met()
{
  return typename MyTemplate<T>::Inner();
}

int main()
{
  MyTemplate<int> foo;

  MyTemplate<int>::Inner bar = foo.met();
}

回答by Prasoon Saurav

You need to add typenamekeyword before MyTemplate<T>::Innerbecause MyTemplate<T>is a dependent scope.

您需要在typename之前添加关键字,MyTemplate<T>::Inner因为它MyTemplate<T>是一个依赖范围。