[英]Calling member function template of class template
我有以下程序(對不起,它相當復雜,但已經是一個較大程序的煮沸版本):
#include <stdio.h>
// two different vector types
template <typename T, int N>
struct Vec1
{
Vec1() { puts("Vec1()"); }
};
template <typename T, int N>
struct Vec2
{
Vec2() { puts("Vec2()"); }
};
// a function wrapper
template <typename T, int N>
struct MyFct
{
template <template <typename, int> class VEC>
static inline VEC<T,N>
apply()
{
puts("MyFct::apply()");
return VEC<T,N>();
}
};
// tester
#if 0
template <typename T, int N, template <typename, int> class FCT>
struct Tester
{
static inline void test()
{
puts("Tester::test");
Vec1<T,N> v1;
v1 = FCT<T,N>::apply<Vec1>();
Vec2<T,N> v2;
v2 = FCT<T,N>::apply<Vec2>();
}
};
#endif
int
main()
{
MyFct<float,16>::apply<Vec1>();
MyFct<int,32>::apply<Vec2>();
// Tester<float,16,MyFct>::test();
return 0;
}
該程序使用#if 0
(不帶Tester
)編譯,但使用#if 1
(使用Tester
)我收到錯誤消息
g++ -Wall -o templatetemplate2a templatetemplate2a.C
templatetemplate2a.C: In static member function 'static void Tester<T, N, FCT>::test()':
templatetemplate2a.C:41:30: error: missing template arguments before '>' token
v1 = FCT<T,N>::apply<Vec1>();
^
templatetemplate2a.C:41:32: error: expected primary-expression before ')' token
v1 = FCT<T,N>::apply<Vec1>();
^
templatetemplate2a.C:43:30: error: missing template arguments before '>' token
v2 = FCT<T,N>::apply<Vec2>();
^
templatetemplate2a.C:43:32: error: expected primary-expression before ')' token
v2 = FCT<T,N>::apply<Vec2>();
這是令人驚訝的,因為直接應用(參見main()
) apply<Vec1>()
和apply<Vec2>()
工作正常。 但是,如果我在Tester::test()
執行相同操作,則會收到錯誤消息。 這是一些名稱范圍問題嗎? Tester
的模板類Vec1
和Vec2
未知的嗎? 我怎樣才能讓他們知道? 還是有其他問題嗎?
apply()
是一個成員函數模板,當使用依賴名稱調用它時,需要使用關鍵字模板告訴編譯器它是一個模板。 注意FCT<T,N>
和MyFct<float,16>
之間的區別,前者取決於模板參數FCT
, T
和N
,而后者則不然。
在模板定義中,模板可用於聲明從屬名稱是模板。
例如
v1 = FCT<T,N>::template apply<Vec1>();
v2 = FCT<T,N>::template apply<Vec2>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.