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

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

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

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

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

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

#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); // 編譯錯(cuò)誤

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

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

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

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) {
        // 省略具體的格式化邏輯
    }
}

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

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

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

相關(guān)文章

最新評(píng)論