【问题标题】:What's the difference between typeid(*this).name() and typeid(this).name() in base class基类中的 typeid(*this).name() 和 typeid(this).name() 有什么区别
【发布时间】: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);
        });

测试结果:

  1. 如果我将 EVENT 定义为“EVENT”类,那么 AnEvent 将被正确处理。
  2. 如果我将 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


【解决方案1】:

1.typeid(*this)、typeid(this)和typeid(varname)有什么区别?

*this 是对对象的左值引用,this 是指向对象的指针。当您在引用上应用typeid 时,您将获得被引用对象的动态类型的类型信息(如果类型是动态的)。当你在指针上应用typeid 时,你会得到指针类型的类型信息。

2.typeid(T).name()返回的值是否相同(保存以与任何编译器和C++版本一起使用)

没有。该名称由实现定义,并且在不同的语言实现中有所不同。

【讨论】:

  • 谢谢!无论共享指针是什么,都只会调用 T == dynamicType 的真正消费者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 2011-01-28
  • 2010-11-06
  • 2011-04-12
  • 1970-01-01
相关资源
最近更新 更多