簡體   English   中英

如何用我自己的模板函數包裝 std::format() ?

[英]How can I wrap std::format() with my own template function?

注意:這個問題使用 C++20,我使用的是 Visual Studio 2022 (v17.2.2)。

我想創建一個模板函數包裝器以允許我使用 std::format 樣式日志記錄。 包裝函數最終會做一些其他與格式無關的東西,這些東西在這里並不重要。

請參閱下面的代碼。 請注意, Log1()工作正常,但使用起來感覺很笨拙。 Log2 () 沒問題,但使用std::vformat()會丟失對日志格式字符串的編譯時檢查。

我真正想做的是Log3() 問題是 Visual Studio (v17.2.2) 不喜歡這個。

有什么辦法可以讓它工作(沒有宏)?

#include <iostream>
#include <format>
#include <string_view>
 
// works fine:  usage is clunky
auto Log1(std::string_view sv)
{
    std::cout << sv;
}
 
// works, but fmt string is checked at runtime - not compile time
template<typename... Args>
auto Log2(std::string_view fmt, Args&&... args)
{
    std::cout << std::vformat(fmt, std::make_format_args(args...));
}
 
// this doesn't work
template<typename... Args>
auto Log3(std::string_view fmt, Args&&... args)
{
    std::cout << std::format(fmt, std::forward<Args>(args)...);
}
 
int main()
{
    Log1(std::format("Hello, {}\n", "world!")); // ok - clunky
    Log2("Hello, {}\n", "world!");              // ok - no compile time checking of fmt string
    Log2("Hello, {:s}\n", 42);                  // ok - throws at runtime
    Log3("Hello, {}\n", "world!");              // ERROR:  doesn't compile
    return 0;
}

您需要P2508 (我的論文)才能着陸,它公開了當前僅用於展示的類型std::basic-format-string<charT, Args...> ,這將允許您編寫:

template<typename... Args>
auto Log3(std::format_string<Args...> fmt, Args&&... args)

在那之前,你可以調皮一點,使用 MSVC 實現的內部幫助器,理解他們可以在任何時候隨意重命名這個類型。

template<typename... Args>
auto Log3(std::_Fmt_string<Args...> fmt, Args&&... args) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM