通过模板函数调用类函数

Calling class function by a template function

本文关键字:函数调用 类函数      更新时间:2023-10-16

我有两个类,有许多函数(函数不能是'静态')。我想每次都通过模板函数调用另一个函数。我试着写模板函数,但我不知道我应该如何用我想要的类函数调用模板函数。我附上一个简单的代码与问题:

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。类fT的成员,它将由编译器推导出来。要实际调用该函数,需要使用(更奇怪的)->*语法。注意,由于成员函数必须在对象上调用,因此需要创建一个T

不需要动态分配。你也可以这样写:

template <typename T>
void Test(void (T::*f)(int), int x)
{
    T a;
    (a.*f)(x);
}

你像这样调用函数Test:

Test(&FirstClass::FirstFunction, 42);