欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++中的std::format?如何實現(xiàn)編譯期格式檢查

 更新時間:2024年04月09日 08:54:41   作者:zhb2000  
C++?20?的?std::format?是一個很神奇、很實用的工具,最神奇的地方在于它能在編譯期檢查字符串的格式是否正確,而且不需要什么特殊的使用方法,只需要像使用普通函數(shù)那樣傳參即可,這篇文章主要介紹了std::format?如何實現(xiàn)編譯期格式檢查,需要的朋友可以參考下

C++ 20 的 std::format 是一個很神奇、很實用的工具,最神奇的地方在于它能在編譯期檢查字符串的格式是否正確,而且不需要什么特殊的使用方法,只需要像使用普通函數(shù)那樣傳參即可。

#include <format>
int a = 1;
std::string s1 = std::format("a: {}", a); // OK
std::string s2 = std::format("a: {}, b: {}", a); // 編譯錯誤

C++ 20 的 std::format 來自一個著名的開源庫 {fmt}。在 C++ 20 之前,fmt 需要為每個字符串字面量創(chuàng)建不同的類型才能實現(xiàn)編譯期格式檢查。fmt 提供了一個 FMT_STRING 宏以簡化使用的流程。

#include <fmt/format.h>
int a = 1;
std::string s1 = fmt::format(FMT_STRING("a: {}"), a); // OK
std::string s2 = fmt::format(FMT_STRING("a: {}, b: {}"), a); // 編譯錯誤

C++ 20 有了 consteval 后就不用這么別扭了。consteval 函數(shù)與以前的 constexpr 函數(shù)不同,constexpr 函數(shù)只有在必須編譯期求值的語境下才會在編譯期執(zhí)行函數(shù),而 consteval 函數(shù)在任何情況下都強制編譯期求值。std::format 就是利用 consteval 函數(shù)在編譯期執(zhí)行代碼,來檢查字符串參數(shù)的格式。

然而 std::format 自身不能是 consteval 函數(shù),只好曲線救國,引入一個輔助類型 std::format_string,讓字符串實參隱式轉(zhuǎn)換為 std::format_string。只要這個轉(zhuǎn)換函數(shù)是 consteval 函數(shù),并且把格式檢查的邏輯寫在這個轉(zhuǎn)換函數(shù)里面,照樣能實現(xiàn)編譯期的格式檢查。

這里我們實現(xiàn)了一個極簡版的 format,可以檢查字符串中 {} 的數(shù)量是否與參數(shù)的個數(shù)相同。format_string 的構(gòu)造函數(shù)就是我們需要的隱式轉(zhuǎn)換函數(shù),它是一個 consteval 函數(shù)。若字符串中 {} 的數(shù)量不對,則代碼會執(zhí)行到 throw 這一行。C++ 的 throw 語句不能在編譯期求值,因此會引發(fā)編譯錯誤,從而實現(xiàn)了在編譯期檢查出字符串的格式錯誤。

namespace my {
    template<class ...Args>
    class format_string {
    private:
        std::string_view str;
    public:
        template<class T>
            requires std::convertible_to<const T &, std::string_view>
        consteval format_string(const T &s)
            : str(s)
        {
            std::size_t actual_num = 0;
            for (std::size_t i = 0; i + 1 < str.length(); i++) {
                if (str[i] == '{' && str[i + 1] == '}') {
                    actual_num++;
                }
            }
            constexpr std::size_t expected_num = sizeof...(Args);
            if (actual_num != expected_num) {
                throw std::format_error("incorrect format string");
            }
        }
        std::string_view get() const { return str; }
    };
    template<class ...Args>
    std::string format(format_string<std::type_identity_t<Args>...> fmt, Args &&...args) {
        // 省略具體的格式化邏輯
    }
}

有一個細節(jié),此處 format 函數(shù)的參數(shù)寫的是 format_string<std::type_identity_t<Args>...>,直接寫 format_string<Args ...> 是無法隱式轉(zhuǎn)換的,因為模板實參推導(dǎo) (template argument deduction) 不會考慮隱式轉(zhuǎn)換,C++ 20 提供了一個工具 std::type_identity 可以解決這個問題。std::type_identity 其實就是一個關(guān)于類型的恒等函數(shù),但是這么倒騰一下就能在模板實參推導(dǎo)中建立非推導(dǎo)語境 (non-deduced context),進而正常地匹配到隱式轉(zhuǎn)換,C++ 就是這么奇怪。

參考資料:c++ - why would type_identity make a difference? - Stack Overflow

到此這篇關(guān)于std::format 如何實現(xiàn)編譯期格式檢查的文章就介紹到這了,更多相關(guān)std::format 如何實現(xiàn)編譯期格式檢查內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論