[英]g++ doesn't compile certain nested templates
When BREAK is defined, g++ 4.7.2 will not compile the following, which I think is valid C++. 当定义BREAK时,g ++ 4.7.2将不会编译以下内容,我认为这是有效的C ++。 It does compile with BREAK defined if the
A<U> tmp
is changed to something else, like A<int> tmp
- while that makes the minimal test case here work, it's no good in my actual application. 如果将
A<U> tmp
更改为其他内容(例如A<int> tmp
,它会使用BREAK进行编译,而这使得最小测试用例在这里起作用,这对我的实际应用程序来说并不好。 Is there anything here that is not legal C++? 这里有什么不合法的C ++吗?
template <typename T>
class B {
};
template <typename T>
class A {
public:
template <typename U> B<U> *alloc_B( );
};
template <typename T> template <typename U>
B<U> *A<T>::alloc_B( ) {
return new B<U>( );
}
#ifdef BREAK
template <typename T>
class C {
public:
template <typename U> void x(B<U> &b) {
A<U> tmp;
B<U> *tmp2;
tmp2 = tmp.alloc_B<U>( );
delete tmp2;
}
};
#endif
int main( ) {
A<int> a;
B<float> *bp = a.alloc_B<float>( );
delete bp;
#ifdef BREAK
C<int> c;
B<float> b;
c.x(b);
#endif
}
The alloc_B
function template is a dependent name. alloc_B
函数模板是从属名称。 You must call it as so: 你必须这样称呼它:
tmp2 = tmp.template alloc_B<U>( );
That's the problem, and that is why it works when you use A<int>
, because the type no longer depends on the template argument U
. 这就是问题,这就是为什么它在你使用
A<int>
,因为类型不再依赖于模板参数U
This is due to one of C++
's annoying parsing rules. 这是由于
C++
的烦人解析规则之一。 When it sees tmp.alloc_B<U>
, this is not interpreted as a template, but as tmp.alloc_B < U
. 当它看到
tmp.alloc_B<U>
,这不会被解释为模板,而是被解释为tmp.alloc_B < U
。 To fix this, you need to explicitly specific this is a template: 要解决此问题,您需要明确指定这是一个模板:
tmp2 = tmp.template alloc_B<U>( );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.