我正在做以下事情:
-
从 derived class 获取带有 3 params 的成员函数指针 .
-
使用 0 params 将其从 the base class 转换为成员函数指针 .
-
使用 the 3 params 将其转换为 the base class .
-
打电话给它 .
它工作正常(到目前为止),但我应该保留它吗?
当前代码说明:
EventsWarehouse用于存储和调用事件:
#include <iostream>
#include <functional>
#include <unordered_map>
class EventsWarehouse
{
public:
typedef std::tuple<AView*, void (AView::*)()> box_t;
typedef std::unordered_multimap<std::string, box_t> boxes_t;
void storeEvent(std::string const &event, AView *v, void (AView::*callback)())
{
this->_events.insert(std::make_pair(event, std::make_tuple(v, callback)));
return ;
}
template<typename... Args>
bool fireEvent(std::string const &event, Args... args)
{
auto it = this->_events.find(event);
AView *v;
void (AView::*callback_)();
void (AView::*callback)(Args...);
for (; it != this->_events.end(); it++)
{
v = std::get<0>(it->second);
callback_ = std::get<1>(it->second);
/*
** CAST #2
** <void (AView::*)()>
** to
** <void (AView::*)(std::string, int, double)>
** before call
*/
callback = reinterpret_cast<void (AView::*)(Args...)>(callback_);
(v->*callback)(args...);
}
return (true);
}
private:
boxes_t _events;
};
查看存储在上面类中的类:
class AView
{
protected:
AView(){}
};
class DerivedView : public AView
{
public:
void fooCallback(std::string s, int i, double d)
{
std::cout << "DerivedView::fooCallback received " << s << ", " << i << ", " << d << std::endl;
return ;
}
};
主要:
int main(void)
{
DerivedView dv;
EventsWarehouse ewh;
/*
** CAST #1
** <void (DerivedView::*)(std::string, int, double)>
** to
** <void (AView::*)()>
** for storing purpose
*/
ewh.storeEvent("event 1", &dv, reinterpret_cast<void (AView::*)()>(&DerivedView::fooCallback));
ewh.fireEvent("event 1", std::string("Hello World"), 42, 84.42);
return (0);
}
1 回答
根据草案n4296 for C 11规范,5.2.10重新解释cast [expr.reinterpret.cast]§10
恕我直言,问题是
fooCallback
仅在DerivedView
类上定义,因此它是 not 类AView
的成员函数 .这是正确的:
提供
v
是AView *
指向DerivedView
但是当您将
void (DerivedView::*)(std::string, int, double)
转换为void (AView::*)(std::string, int, double)
时它们是不同的类型,因此转换未指定它可以工作,因为非静态非虚拟成员函数的常见实现只是一个普通(非成员)函数,其隐藏参数为
this
. 因此,指向成员的指针只存储该函数的地址,并使用指向DerivedView
的指针正确调用它,从而得到预期的结果 . 但是不同的实现也可以存储实际类型并引发异常(或执行任何其他操作) .TL / DR:当您从
void (DerivedView::*)(std::string, int, double)
转换为void (AView::*)(std::string, int, double)
结束时,不会将指向成员的指针强制转换为其原始类型并调用未定义的行为 .