Generic member function pointer

主宰稳场 提交于 2019-12-08 13:06:33

You could create a generic templated function which accepts the signature you are interested in, pass in the instance of the object and the pointer to the member function. For example:

template<typename T>
void CallObjectMethod(int(T::*func)(int), T& obj, int val)
{
    cout << (obj.*func)(val);
}

Now to call it like you mentioned in your example:

X x, x1;
CallObjectMethod(&X::echoX, x, 10);
CallObjectMethod(&X::echoX, x1, 20);

For object Y you could do something like:

Y y, y1;
CallObjectMethod(&Y::echoY, y, 10);
CallObjectMethod(&Y::echoY, y1, 20);

"For example, X and Y have echoX and echoY methods with the same signature"

Afaik they dont have the same signature, they have an implicit first argument to the class instance. Usually you would choose an std::function to get rid of the first argument.

#include <functional>

class X { public: int echoX(int v) {return v; } };

class Y { public: int echoY(int v) {return v; } };

typedef std::function<int(int)> IntFunction;

int echo(IntFunction func, int v)
{
    return func(v);
}

int main()
{
    int v = 5;
    X x;
    Y y;
    int a = echo(std::bind(&X::echoX, x, std::placeholders::_1), v);
    int b = echo(std::bind(&Y::echoY, y, std::placeholders::_1), v);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!