使用 fmt 格式化 wstring 失败:没有用于调用 'format(const wchar_t [17], int)' 的匹配函数

format wstring with fmt fails: no matching function for call to 'format(const wchar_t [17], int)'

我在 windows 10 中使用带有代码块 20.03 和 gcc 8.1.0 的 fmt 8.0.1,并且在尝试编译此代码时

#include <fmt/format.h>

int main(){
    std::wstring a = fmt::format(L"The answer is {}", 42);
}

我收到以下错误

main.cpp: In function 'int main()':
main.cpp:4:57: error: no matching function for call to 'format(const wchar_t [17], int)'
     std::wstring a = fmt::format(L"The answer is {}", 42);
                                                         ^
In file included from D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:44,
                 from main.cpp:1:
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/core.h:2885:17: note: candidate: 'std::__cxx11::string fmt::v8::format(fmt::v8::format_string<T ...>, T&& ...) [with T = {int}; std::__cxx11::string = std::__cxx11::basic_string<char>; fmt::v8::format_string<T ...> = fmt::v8::basic_format_string<char, int>]'
 FMT_INLINE auto format(format_string<T...> fmt, T&&... args) -> std::string {
                 ^~~~~~
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/core.h:2885:17: note:   no known conversion for argument 1 from 'const wchar_t [17]' to 'fmt::v8::format_string<int>' {aka 'fmt::v8::basic_format_string<char, int>'}
In file included from main.cpp:1:
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:2784:13: note: candidate: 'template<class Locale, class ... T, typename std::enable_if<fmt::v8::detail::is_locale<Locale>::value, int>::type <anonymous> > std::__cxx11::string fmt::v8::format(const Locale&, fmt::v8::format_string<T ...>, T&& ...)'
 inline auto format(const Locale& loc, format_string<T...> fmt, T&&... args)
             ^~~~~~
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:2784:13: note:   template argument deduction/substitution failed:
In file included from D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:44,
                 from main.cpp:1:
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:2783:11: error: no type named 'type' in 'struct std::enable_if<false, int>'
           FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
           ^~~~~~~~~~~~~

编译命令:

g++ main.cpp "D:\descargas\fmt-8.0.1\fmt-8.0.1\build\libfmt.a"

根据 documentation 你应该包括 fmt/xchar.h 以获得 wchar_t 支持:

#include <fmt/xchar.h>

int main() {
  std::wstring a = fmt::format(L"The answer is {}", 42);
}

godbolt