通过模板函数调用类函数
Calling class function by a template function
我有两个类,有许多函数(函数不能是'静态')。我想每次都通过模板函数调用另一个函数。我试着写模板函数,但我不知道我应该如何用我想要的类函数调用模板函数。我附上一个简单的代码与问题:
class FirstClass
{
public:
FirstClass()
{
int y = 7;
y++;
}
void FirstFunction(int x)
{
x++;
}
};
class SecondClass
{
public:
SecondClass()
{
int y = 7;
y++;
}
void SecondFunction(int y)
{
y--;
}
void ThirdFunction(int y)
{
y--;
}
};
template<class OBJECT, void (*FUNCTION)>
void Test(int x)
{
OBJECT *a = new OBJECT();
a->FUNCTION();
delete a;
}
void main()
{
Test<FirstClass, &FirstClass.FirstFunction>(5);
Test<SecondClass, &SecondClass.SecondFunction>(5);
Test<SecondClass, &SecondClass.ThirdFunction>(5);
}
谢谢…
c++编译器特别擅长推断类型。与其直接指定你想调用的成员函数的类型,为什么不让编译器为你这样做呢?
template <typename T>
void Test(void (T::*f)(int), int x)
{
auto a = new T;
(a->*f)(x);
delete a;
}
注意奇怪的T::*
语法。它说f
是一个指向成员函数的指针,该函数返回void
并接受int
。类f
是T
的成员,它将由编译器推导出来。要实际调用该函数,需要使用(更奇怪的)->*
语法。注意,由于成员函数必须在对象上调用,因此需要创建一个T
。
不需要动态分配。你也可以这样写:
template <typename T>
void Test(void (T::*f)(int), int x)
{
T a;
(a.*f)(x);
}
你像这样调用函数Test
:
Test(&FirstClass::FirstFunction, 42);
相关文章:
- 使用宏调用类函数
- 从 c++ 中派生类的析构函数调用虚函数
- 使用另一个函数调用一个函数(都在类中)时出现问题.没有错误代码C++
- C++虚拟函数:基类函数是调用的,而不是派生的
- Python在不引用类名的情况下调用类函数
- 需要"模板<>"语法 --> 通过函数调用类模板
- C++ - 从另一个类构造函数调用类构造函数
- 从 LUA 脚本调用类函数C++
- 在定义变量时调用类函数
- 在没有限定的情况下从 T 构造函数调用类 T 的纯虚拟实现?
- 你如何调用类函数,但使用不同的类对象
- 从构造函数调用类函数或使用智能指针
- 在 c++ 中通过指针从另一个类调用类函数
- 加载cygwin C++dll,调用类函数
- 不能调用类函数(参数化类)
- c++从非成员调用类函数/数据
- 通过信号和时隙系统调用类函数
- 子类中的虚拟函数调用父函数一次
- 通过此指针从静态函数调用类函数
- 通过模板函数调用类函数