【发布时间】:2020-12-04 06:27:08
【问题描述】:
class Event
{
public:
virtual std::string getEventType()
{
return typeid(*this).name();
}
}
class NotWorkEvent
{
public:
virtual std::string getEventType()
{
return typeid(this).name();
}
};
struct EventCallBak
{
long funcId_;
EventConsumeFunc func_;
};
class EventBus
{
public:
EventBus()
: callbackId_(0)
{}
void publish(std::shared_ptr<Event> event)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
for (auto msgCb : callbackMap_)
{
if (event->getEventType() == msgCb.first)
{
for (EventCallBak cb : msgCb.second)
{
cb.func_(event);
}
}
}
}
template<typename T>
long registerHandler(EventConsumeFunc func)
{
std::string type = typeid(T).name();
std::lock_guard<std::recursive_mutex> lockGuard(mutex_);
EventCallBak cb;
cb.funcId_ = callbackId_++;
cb.func_ = func;
auto it = callbackMap_.find(type);
if (it == callbackMap_.end())
{
std::vector<EventCallBak> cbs;
cbs.push_back(cb);
callbackMap_[type] = cbs;
}
else
{
it->second.push_back(cb);
}
return cb.funcId_;
}
std::map<std::string, std::vector<EventCallBak>> callbackMap_;
mutable std::recursive_mutex mutex_;
long callbackId_;
};
这里是测试代码:
class AnEvent : public Event
{
};
std::shared_ptr<EventBus> eventBus = std::make_shared<EventBus>();
int eventCaller = eventBus_->registerHandler<AnEvent>(
[&](std::shared_ptr<Event> event)
{
std::shared_ptr<AnEvent> typedEvent = std::dynamic_pointer_cast<AnEvent>(event);
EXPECT_TRUE(typedEvent != nullptr);
});
测试结果:
- 如果我将 EVENT 定义为“EVENT”类,那么 AnEvent 将被正确处理。
- 如果我将 EVENT 定义为“NotWorkEvent”类,则不会触发 AnEvent。
我的问题:
1.typeid(*this)、typeid(this)和typeid(varname)有什么区别?
2. 模板中的 typeid(T).name() 和 typeid(*this) 返回的值是否相同(保存以与任何编译器和 C++ 版本一起使用)?
【问题讨论】:
-
如果我使用 typeid(this) 只返回基本名称。 typeid(*this) 的“*******5EventE”和“*******7AnEventE”
标签: c++ templates type-deduction typeid