我有很多从同一个基类派生的类,并且我试图避免为所有派生类编写格式化程序。我尝试只为基类实现 std::formatter,但将派生类对象/引用传递给 std::format 将触发编译错误。
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.32.31326\include\format(1496): 错误 C2665: 'std::_Format_arg_traits<_Context>::_Phony_basic_format_arg_constructor': 没有5 个重载可以使用 [ _Context=std::format_context ] 转换所有参数类型...
最小代码如下:
#include <format>
#include <iostream>
#include <string>
using namespace std;
struct Base
{
virtual string ToString()
{
return "Base";
}
};
struct D1 : public Base
{
string ToString() override
{
return "D1";
}
};
template <typename CharT> struct ::std::formatter<Base, CharT> : ::std::formatter<::std::string>
{
// parse is inherited from formatter<string>.
template <typename FormatContext> auto format(Base &e, FormatContext &ctx) const
{
::std::string name = …Run Code Online (Sandbox Code Playgroud)