![](/img/trans.png)
[英]typeid.name() not changing when iterating through a vector. Dynamic cast and typeid a base class pointer
[英]What's the difference between typeid(*this).name() and typeid(this).name() in base class
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);
});
測試結果:
我的問題:
1.typeid(*this)、typeid(this)和typeid(varname)有什么區別?
2. 模板中的 typeid(T).name() 和 typeid(*this) 返回的值是否相同(保存以與任何編譯器和 C++ 版本一起使用)?
1.typeid(*this)、typeid(this)和typeid(varname)有什么區別?
*this
是對 object 的左值引用, this
是指向 object 的指針。 當您在引用上應用typeid
時,您將獲得所引用 object 的動態類型的類型信息(如果類型是動態的)。 當您在指針上應用typeid
時,您將獲得指針類型的類型信息。
2. typeid(T).name() 返回的值是否相同(保存以與任何編譯器和 C++ 版本一起使用)
不,名稱是實現定義的,並且在不同的語言實現中是不同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.