本文介绍了“事件”的C ++映射和成员函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设法写一个模板类来工作,就像一个回调,从这个问题的接受的答案学习。

I've managed to write a template class to work like a callback, learned from the accepted answer of this question How to define a general member function pointer.

我希望有一个字符串键和回调值的映射以便我可以调用匹配字符串的正确回调。这将是好的,但我需要地图支持来自不同的类的回调。现在它只能工作在一个类。它可以是任何类,因为模板,但只有来自同一类的回调的集合。

I wish to have a map of string keys and callback values so that I can invoke the proper callback that matches a string. This would be fine but I need the map to support callbacks from different classes. Right now it can only work with one class. It can be any class because of the template but only a collection of callbacks from the same class.

class Apple {
public:
    void Red () {
        cout << "aa";
    }
};

class Orange {
public:
    void Blue () {
        cout << "bb";
    }
};

template <typename T>
class Callback {
    T *obj;
    void (T::*ptr) (void);

public:
    Callback (T *obj, void (T::*ptr) (void)) : obj (obj), ptr (ptr) {

    }

    void Call () {
        (obj->*ptr) ();
    }
};

我可以这样使用

Apple apple;
Orange orange;
Callback <Apple> callA (&apple, &Apple::Red);
Callback <Orange> callB (&orange, &Orange::Blue);
callA.call ();
callB.call ();

std::map <std::string, Callback <Apple>> appleCallbacks;

我想要这样做

std::map <std::string, Callback <anything>> anyCallbacks;

我打算用一堆共享相同基类的类,

I plan to use this with a bunch of classes that share the same base class and have functions are identical to each other in definition except for the name and which class it belongs to.

class Base { };

class ChildA : public Base {
public:
    void Talk ();
}

class ChildB : public Base {
public:
    void Walk ();
}

所以如果这个工作,我可以把Talk ()到地图中。

So if this worked I would be able to put both Talk () and Walk () into the map.

这是可能的还是我的观点有缺陷开始?

Is this possible at all or is my point of view flawed to begin with?

推荐答案

Madness说,这样:不要将回调绑定到特定的类。而是使用 std :: function< Signature> 对象并创建合适的函数对象:当你需要对不同的类进行操作时,你还需要对不同类型的对象。使用 std :: function< ...> 应该做的窍门,例如:

Madness lies, this way: Don't bind callbacks to specific classes. Instead, use a std::function<Signature> object and create suitable function objects: when you need to operate on different classes, you also need to operate on objects of different types. Using a std::function<...> should do the trick, e.g.:

std::map<std::string, std::function<void()>> operations;
operations["talk"] = std::bind(&ChildA::Talk, ChildA());
operations["walk"] = std::bind(&ChildB::Walk, ChildB());
operations["talk"]();

这篇关于“事件”的C ++映射和成员函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 01:17