我正在嘗試在地圖中存盤事件的回呼。由于每個類應該有一個回呼,我目前將其typeid(<eventClass>).name()用作鍵,將 std::function 用作值。我遇到的問題是在注冊回呼時,我需要事件的型別,我想出的唯一可能的解決方案是將事件類作為模板引數傳遞。這是一個我想“優化”的作業示例:
std::map<Widget *, std::map<std::string, std::function<void(Widget*, Event &)>>> handlers;
template<typename T, std::enable_if_t<std::is_base_of_v<Event, T>, bool> = true>
void setCallback(Widget *obj, const std::function<void(Widget *, T &event)> &callback) {
handlers[obj].insert(std::make_pair(typeid(T).name(), reinterpret_cast<const std::function<void(Widget *, Event &)> &>(callback)));
}
void fire(Widget *obj, Event &event) {
auto it = handlers.find(obj);
if (it != handlers.end()) {
auto it2 = it->second.find(typeid(event).name());
if (it2 != it->second.end()) {
it2->second(obj, event);
return; // debug
}
}
printf("No handler found!\n"); // debug
}
由于setCallback函式中的模板引數,使用該方法如下所示:
void callback(Widget *, BarEvent &barEvent) {
printf("%d\n", barEvent.getFoo());
}
void callback2(Widget *, FooEvent &fooEvent) {
printf("%d\n", fooEvent.getFoo());
}
int main() {
Widget *obj = new Widget();
Widget *obj2 = new Widget();
setCallback<BarEvent>(obj, callback);
setCallback<FooEvent>(obj2, callback2);
BarEvent event;
fire(obj, event);
fire(obj2, event);
FooEvent event2;
fire(obj, event2);
fire(obj2, event2);
delete obj;
delete obj2;
return 0;
}
在設定回呼時必須傳遞模板引數很容易出錯并且只是“開銷”,因為事件類已經在回呼中。有沒有辦法獲取函式中callback引數的第二個引數的型別setCallback?
如果可能,該函式應如下所示:
void setCallback(Widget *widget, const std::function<void(Widget *, Event &)> &callback) {
handlers[widget].insert(std::make_pair(typeid(<2nd param of callback>).name(), callback));
}
uj5u.com熱心網友回復:
這是一些不使用reinterpret_cast并自動推導的代碼(在許多但不是所有情況下)。代碼完整且可運行,但被純文本打斷(比等寬注釋更具可讀性)。
#include <vector>
#include <map>
#include <typeinfo>
#include <typeindex>
#include <iostream>
#include <type_traits>
struct Event
{
virtual ~Event() = default;
};
struct FooEvent : Event {};
struct BarEvent : Event {};
template <typename>
struct extract_second_argument;
下一節是我們從普通函式和std::function物件中提取第二個引數型別的管道。請注意,這些并不是所有可以呼叫的東西。該機制不適用于 lambda 和其他函式物件,或指向成員的指標。
template <typename A, typename B, typename C, typename ... X>
struct extract_second_argument<A (*)(B, C, X...)>
{
using type = std::remove_reference_t<C>;
};
template <typename A, typename B, typename C, typename ... X>
struct extract_second_argument<std::function<A(B, C, X...)>>
{
using type = std::remove_reference_t<C>;
};
template <typename T>
using extract_second_argument_t = typename extract_second_argument<T>::type;
這是我們的(簡化的)Widget。它包含的不是一個,而是兩個不同的回呼容器!選擇一個你喜歡的。請注意,盡管速度較慢(執行更多動態轉換),但純向量可能更受歡迎,因為它與基于映射的向量不同,它支持回呼層次結構。您可以為 Parent 事件和 Child 事件添加回呼,如果 Child 被觸發,兩個回呼都將被呼叫。您是否需要這個由您決定。這兩種機制都允許每個事件型別有許多回呼(這在大多數情況下是可取的,但如果它不是你的一杯茶,只需使用普通地圖而不是多地圖)。
struct Widget {
using Callback = std::function<void(Widget&, Event&)>;
using CallbackList = std::vector<Callback>;
using CallbackMap = std::multimap<std::type_index, Callback>;
CallbackList callbacks;
CallbackMap callbacks2;
這添加了任何性質的回呼(普通函式、std::function、 lambda ......)但沒有引數型別推導。
template <typename EV>
void addCallbackImpl(std::function<void(Widget&, EV&)> cb)
{
這個包裝紙是機器的心臟。請注意,它使用 的多型性質Event。
auto wrapper = [=](Widget& w, Event& ev) {
auto* realEv = dynamic_cast<EV*>(&ev);
if (realEv) cb(w, *realEv);
};
我們的兩個回呼容器(您只需要一個)。
callbacks.push_back(wrapper);
callbacks2.insert({std::type_index(typeid(EV)), wrapper});
}
這將嘗試添加一個回呼,它要么是一個普通的函式指標,要么是一個std::function. 它不適用于 lambda,但會進行引數型別推導。
template <typename F>
void addCallback(F cb)
{
addCallbackImpl<extract_second_argument_t<F>>(cb);
};
在兩種容器中呼叫回呼。
void fire (Event& ev)
{
std::cout << "callbacks with method 1\n";
for (auto& cb: callbacks) cb(*this, ev);
std::cout << "callbacks with method 2\n";
auto range = callbacks2.equal_range(std::type_index(typeid(ev)));
for (auto& cb = range.first; cb != range.second; cb) cb->second(*this, ev);
}
};
現在是測驗驅動程式。
void cb1 (Widget&, FooEvent&)
{
std::cout << "cb1 called\n";
}
void cb2 (Widget&, BarEvent&)
{
std::cout << "cb2 called\n";
}
int main()
{
Widget w;
w.addCallback(cb1);
w.addCallback(cb2);
FooEvent foo;
BarEvent bar;
w.fire(foo);
w.fire(bar);
}
現場演示
uj5u.com熱心網友回復:
不知道我是否理解這個問題。如果是關于獲取 a 的引數之一的型別,則std::function可以使用部分專業化。部分特化不適用于函式模板,因此我們需要使用輔助型別:
#include <functional>
#include <iostream>
struct Widget {};
struct Event {
static void sayHello(){ std::cout << "hello\n";}
};
template <typename F> struct event_from_function;
template <typename EVENT>
struct event_from_function< std::function<void(Widget*,EVENT&)>> {
using type = EVENT;
};
template <typename F>
void foo(F f) {
event_from_function<F>::type::sayHello();
}
int main() {
std::function<void(Widget*,Event&)> f;
foo(f);
}
現場演示。
sayHello并且foo只是通過Event從T(即std::function<void(Widget*,Event&>)獲取引數型別()來獲取一些輸出的示例。
uj5u.com熱心網友回復:
更新示例,每個事件僅允許一個回呼。
#include <functional>
#include <iostream>
#include <unordered_map>
struct Event
{
};
struct FooEvent : public Event {};
struct BarEvent : public Event {};
class Widget
{
public:
// use a function pointer for automatic template deduction
// todo add specialization for member functions of classes
template<typename event_t>
void set_callback(void (*fn)(Widget&, event_t))
{
// static asserts tend to give more readable error messages then SFINAE (std::enable_if_t)
static_assert(std::is_base_of_v<Event, event_t>, "not a valid event type");
// get the callback map for this for this event type.
// basically there is one static map for each event_t
// and event registrations are done based on the widget instance id (m_id)
auto& callback_map = get_callback_map<event_t>();
// set the callback for this instance of the widget to the passed function
callback_map[m_id] = std::function{ fn };
}
// select an event firing implementation based on the even type
template<typename event_t>
void fire_event(const event_t& ev)
{
static_assert(std::is_base_of_v<Event, event_t>, "not a valid event type");
// again get the callback map
auto& callback_map = get_callback_map<event_t>();
auto it = callback_map.find(m_id);
if (it == callback_map.end()) return;
auto callback = it->second;
callback(*this, ev);
}
private:
// static function for generating member id's
static std::size_t get_id()
{
static std::size_t id{ 0 };
return id;
}
// get the singleton handler map for event_t
template<typename event_t>
static auto& get_callback_map()
{
static std::unordered_map<std::size_t,std::function<void(Widget&, event_t)>> callback_map;
return callback_map;
}
// the widget's instance id
std::size_t m_id{ get_id() };
};
//---------------------------------------------------------------------------------------------------------------------
void foo_callback(Widget& widget, FooEvent foo_event)
{
std::cout << "FooEvent\n";
};
//---------------------------------------------------------------------------------------------------------------------
void bar_callback(Widget& widget, BarEvent bar_event)
{
std::cout << "BarEvent\n";
};
//---------------------------------------------------------------------------------------------------------------------
int main()
{
Widget w1;
Widget w2;
FooEvent foo_event;
BarEvent bar_event;
// register handlers
w1.set_callback(foo_callback);
w2.set_callback(bar_callback);
// show reactions to events
// w1 will react to foo_event but not to bar_event
std::cout << "w1 reactions : \n";
w1.fire_event(foo_event);
w1.fire_event(bar_event);
std::cout << "w2 reactions : \n";
w2.fire_event(foo_event);
w2.fire_event(bar_event);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/389432.html
