WiderGamer
WiderGamer

Reputation: 13

How the template deduction for functions work in C++?

I have come across this piece of code that is made for an Event Dispatcher. it will first check to see if the type of event is the one it wants then it will run a templated function with the event as its argument, I have a problem with the syntax of the argument for that function ( What does the (*(T*)&m_Event) mean, why an asterisk before T? why one after T?)

class EventDispatcher
    {
        template<typename T>
        using EventFn = std::function<bool(T&)>;
    public:
        EventDispatcher(Event& event)
            : m_Event(event)
        {
        }

        template<typename T>
        bool Dispatch(EventFn<T> func)
        {
            if (m_Event.GetEventType() == T::GetStaticType())
            {
                m_Event.m_Handled = func(*(T*)&m_Event);
                return true;
            }
            return false;
        }
    private:
        Event& m_Event;
    };

Upvotes: 1

Views: 205

Answers (1)

Michael Kenzel
Michael Kenzel

Reputation: 15951

(T*) is a C-style cast that is used here to cast &m_Event to a pointer to a T. The result of all of that is then dereferenced (the leftmost *). In the end, this is just a suspiciously complicated way of passing a reference to the object m_Event to the call to func (unless there's some operator overloading going on that we should be aware of).

Generally, this code doesn't look great to me. The fact that a cast like that would be needed here is concerning. Chances are this whole contraption is actually invoking undefined behavior, but it's hard to say without knowing what, e.g., the whole GetEventType() and GetStaticType() business is about and what all the types involved here actually are…

PS: the parameter func would probably better be passed by reference here.

Upvotes: 1

Related Questions