[英]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.