![](/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.