spdlog icon indicating copy to clipboard operation
spdlog copied to clipboard

C2338: Cannot format an argument. To make type T formattable provide a formatter<T> specialization.

Open ItsNovaAndCrap opened this issue 2 years ago • 4 comments

Before I start, I know that this issue already exists. But, I am quite stupid and don't know what to do. I am currently following The Cherno's game engine series and am on the Event System episode.

This class gives me the error:

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;
};

Tell me if I need to give more information please.

ItsNovaAndCrap avatar Jan 03 '23 17:01 ItsNovaAndCrap

Also, I am sure that it's either this:

template<typename T>
using EventFn = std::function<bool(T&)>;

or this:

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;
}

because they are the only things that are using template<typename T>.

ItsNovaAndCrap avatar Jan 03 '23 17:01 ItsNovaAndCrap

That error message is reported by the fmt library, which needs to specialize fmt::formatter<T> to tell the fmt library how to format T. See fmt document: https://fmt.dev/9.1.0/api.html#formatting-user-defined-types

tt4g avatar Jan 03 '23 21:01 tt4g

I also encountered this problem, added specialize fmt:: formatter, or not. Since my base class is an abstract class, it is possible to provide this partial specialization in the subclass(class WindowResizeEvent : public Event). Is there any other solution besides this method?

template<>
struct fmt::formatter<Act::Event> : fmt::formatter<std::string>
{
    auto format(Act::Event event, format_context &ctx) -> decltype(ctx.out())
    {
        return format_to(ctx.out(), "({})", event.ToString());
    }
};

cy-arctique avatar May 11 '23 01:05 cy-arctique

@cy-arctique Please ask in the fmt repository.

tt4g avatar May 11 '23 13:05 tt4g