调用类模板的成员函数模板
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()
内执行相同的操作,则会收到错误消息。这是某个名称范围问题吗?模板类是否Vec1
,Vec2
Tester
内部未知?我怎样才能让他们知道?还是有其他问题?
>apply()
是一个成员函数模板,在使用依赖名称调用编译器时,需要使用关键字 template 告诉编译器它是一个模板。注意FCT<T,N>
和MyFct<float,16>
的区别,前者取决于模板参数FCT
、T
和N
,而后者则不然。
在模板定义中,模板可用于声明依赖名称是模板。
例如
v1 = FCT<T,N>::template apply<Vec1>();
v2 = FCT<T,N>::template apply<Vec2>();
相关文章:
- 是否可以获取成员函数模板参数的拥有对象?
- 实例化多种类型的成员函数模板
- C++:递归成员函数模板
- C++成员函数模板将成员函数指针作为模板参数
- 类和成员函数模板专用化出错
- 调用类模板的成员函数模板
- 课堂中成员函数模板的明确实例
- 专用和/或重载具有可变参数的成员函数模板
- 具有可变参数的类成员函数模板部分专用化
- 将 PIMPL 习惯用法与成员函数模板一起使用(无需预先了解所有可能的数据类型)
- 澄清了使用 enable_if 的成员函数模板专用化
- 是否可以从指向成员函数模板参数的指针推断类类型
- 成员函数模板推演指南或其他方法让编译器知道如何调用函数
- 成员函数模板不会在 clang 上编译,但在 GCC 上编译
- 类模板的成员函数模板找不到定义,尽管存在显式实例化。不链接
- 成员函数模板参数的部分专业化
- 在C++中创建成员函数模板专用化
- 要求派生类提供成员函数模板
- 实例化错误后成员函数模板的专业化,以及成员函数的顺序
- 使用提升::函数的成员函数模板