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
Compiling error on template method, return is instance from inner class
提问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>::Inner
as a proper class. How can I fix this? I've tried sticking the typename
keyword 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 typename
in 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::met
is a dependent name, so you need to add the typename
keyword 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 typename
keyword before MyTemplate<T>::Inner
because MyTemplate<T>
is a dependent scope.
您需要在typename
之前添加关键字,MyTemplate<T>::Inner
因为它MyTemplate<T>
是一个依赖范围。