C++ 委托学习笔记

class A{

public:

           void Func(int){...}

};

要取得Func函数指针,void (A::*pFunc)(int)=&A::Func;

::*是一个特殊操作符,表示pFunc是一个指针,指向A的成员。获取成员函数的地址不能通过类对象来获取,必须通过类名获取,而且要加上取地址操作。

那么如果通过指针来调用该函数,成员函数都隐含了一个this参数,表示函数要操作的对象,我们只获取了函数的指针,还缺少一个对象作为this参数,为了这个目的,我们先创建一个对象,然后通过该对象来调用成员函数指针:

A a; 

( a.*pFunc)(10);



A* pa=&a;



(pa->*pFunc)(11);

对于可变参数模板,一般使用情况是不需要解包的,只需要做一个类似转发的工作即可

#include <iostream>

#include <string>

using namespace std;

template <class T, class R, typename... Args>

class  MyDelegate

{

public:

    MyDelegate(T* t, R(T::* f)(Args...)/*需要一个入参为可变参数的函数指针*/) :m_t(t),  m_f(f) {}

    R operator()(Args&&... args)

    {

        return (m_t->*m_f)(std::forward<Args>(args) ...);

    }

private:

    T* m_t;

    R(T::* m_f)(Args...);

};

using pF = void(*)(int, int);

template <class T, class R, typename... Args>

MyDelegate<T, R, Args...> CreateDelegate(T* t, R(T::* f)(Args...))

{

    return MyDelegate<T, R, Args...>(t, f);

}

struct A

{

    void Fun(int i) { cout << i << endl; }

    void Fun1(int i, double j) { cout << i + j << endl; }

};

int main()

{

    A a;

    auto d = CreateDelegate(&a, &A::Fun); //创建委托 &A::Fun 传入CreateDelegate相当于 void(A::*f)(int)

    d(1); //调用委托,将输出1

    auto d1 = CreateDelegate(&a, &A::Fun1); //创建委托

    d1(1, 2.5); //调用委托,将输出3.5

    // my test

    void(A:: * pFunc)(int) = &A::Fun;

    auto d05 = CreateDelegate(&a, pFunc);

    (a.*pFunc)(1);

    (&a->*pFunc)(1);

    return 0;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章