![](/img/trans.png)
[英]Why the memory allocation like this when the const reference release to a different type in g++4.7.3
[英]Code won't compile with G++4.7.3 when templated function calls are chained a specific way
请注意,我可以绕开这个问题,我只是好奇为什么这实际上发生了。
我正在尝试在另一个模板函数中的返回值上调用一个模板函数。 我用模板对象作为模板参数调用模板函数。 模板化对象是使用外部模板参数定义的。
#include <string>
class Class
{
public:
static Class& define( std::string name ) {
return *new Class();
}
template<typename C, typename... Args>
Class& constructor() {
// .. Add the constructor...
return *this;
}
};
template<typename T>
class iVector {
T x; T y;
iVector() : x( 0 ), y( 0 ) {}
iVector( T x, T y ) : x( x ), y( y ) {}
};
typedef iVector<int> Vector;
Class& registerVector( std::string name ) {
// This works as expected.
Class& c = Class::define( name )
.constructor< Vector >()
.constructor< Vector, int, int >();
return c;
}
// Outer templated function.
template<typename T>
Class& registerVector( std::string name ) {
Class& c = Class::define( name )
.constructor< iVector<T> >( )
// This however throws a compiler error
.constructor< iVector<T>, T, T >();
return c;
}
int main() {
registerVector( "Vector" );
registerVector< iVector<int> >( "Vector" );
}
仅当两个功能链接在一起并且作为功能模板参数传递的类型使用外部功能模板类型时,才出现此问题。 为什么会这样呢? 这是GCC错误吗? GCC错误:
TempTest.cpp: In function ‘Class& registerVector(std::string)’:
TempTest.cpp:46:27: error: expected primary-expression before ‘,’ token
TempTest.cpp:46:29: error: declaration of ‘Class T’
TempTest.cpp:41:10: error: shadows template parm ‘class T’
TempTest.cpp:46:34: error: expected initializer before ‘>’ token
因为这些函数是在模板中调用的,所以您需要使用template
关键字来消除歧义,以作为对函数模板的调用:
Class& c = Class::define( name )
.template constructor< iVector<T> >()
.template constructor< iVector<T>, T, T >();
有关更多信息,请参见此常见问题解答 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.