C++ {fmt}库fmt::vformat结合宽字符串编译失败问题求助
解决fmt 10.0.0中宽字符串vformat编译失败问题
在使用fmt 10.0.0版本时,调用fmt::vformat处理宽字符串(std::wstring)并搭配fmt::make_wformat_args会触发编译错误,错误提示为:
error: no matching function for call to 'vformat(std::wstring&, fmt::v10::format_arg_store<fmt::v10::basic_format_context<std::back_insert_iterator<fmt::v10::detail::buffer<wchar_t> >, wchar_t>, int>)'
编译失败的代码示例
#include <fmt/xchar.h> #include <string> #include <iostream> int main() { int arg_1 = 12; std::wstring format = L"Hello {}"; std::wstring test = fmt::vformat(format, fmt::make_wformat_args(arg_1)); std::wcout << test; return 0; }
可正常编译的窄字符串版本对比
#include <fmt/xchar.h> #include <string> #include <iostream> int main() { int arg_1 = 12; std::string format = "Hello {}"; std::string test = fmt::vformat(format, fmt::make_format_args(arg_1)); std::cout << test; return 0; }
解决方案
问题根源在于编译器无法自动推导宽字符版本fmt::vformat的重载,可通过以下两种方式解决:
1. 显式指定fmt::vformat的模板参数
直接指定模板参数为wchar_t,明确调用宽字符版本的vformat:
std::wstring test = fmt::vformat<wchar_t>(format, fmt::make_wformat_args(arg_1));
2. 使用fmt::wformat_string约束格式字符串(C++20及以上)
如果项目支持C++20,用fmt::wformat_string包装格式字符串,让编译器自动匹配正确的重载:
#include <fmt/xchar.h> #include <string> #include <iostream> int main() { int arg_1 = 12; fmt::wformat_string<int> format = L"Hello {}"; std::wstring test = fmt::vformat(format, fmt::make_wformat_args(arg_1)); std::wcout << test; return 0; }
注意:修改后建议清理编译缓存再重新编译,确保头文件和模板推导逻辑生效。
内容的提问来源于stack exchange,提问作者jayphen
相关产品推荐
相关产品推荐

