C++中的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 來自一個(gè)著名的開源庫 {fmt}。在 C++ 20 之前,fmt 需要為每個(gè)字符串字面量創(chuàng)建不同的類型才能實(shí)現(xiàn)編譯期格式檢查。fmt 提供了一個(gè) 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); // 編譯錯(cuò)誤C++ 20 有了 consteval 后就不用這么別扭了。consteval 函數(shù)與以前的 constexpr 函數(shù)不同,constexpr 函數(shù)只有在必須編譯期求值的語境下才會在編譯期執(zhí)行函數(shù),而 consteval 函數(shù)在任何情況下都強(qiáng)制編譯期求值。std::format 就是利用 consteval 函數(shù)在編譯期執(zhí)行代碼,來檢查字符串參數(shù)的格式。
然而 std::format 自身不能是 consteval 函數(shù),只好曲線救國,引入一個(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è)極簡版的 format,可以檢查字符串中 {} 的數(shù)量是否與參數(shù)的個(gè)數(shù)相同。format_string 的構(gòu)造函數(shù)就是我們需要的隱式轉(zhuǎn)換函數(shù),它是一個(gè) consteval 函數(shù)。若字符串中 {} 的數(shù)量不對,則代碼會執(zhí)行到 throw 這一行。C++ 的 throw 語句不能在編譯期求值,因此會引發(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 ...> 是無法隱式轉(zhuǎn)換的,因?yàn)?a rel="nofollow" target="_blank">模板實(shí)參推導(dǎo) (template argument deduction) 不會考慮隱式轉(zhuǎn)換,C++ 20 提供了一個(gè)工具 std::type_identity 可以解決這個(gè)問題。std::type_identity 其實(shí)就是一個(gè)關(guān)于類型的恒等函數(shù),但是這么倒騰一下就能在模板實(shí)參推導(dǎo)中建立非推導(dǎo)語境 (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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c++中vector<int>和vector<int*>的用法及區(qū)別
這篇文章主要介紹了c++中vector<int>和vector<int*>的用法及區(qū)別,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2013-10-10
C++高并發(fā)內(nèi)存池的整體設(shè)計(jì)和實(shí)現(xiàn)思路
這篇文章主要介紹了C++高并發(fā)內(nèi)存池的整體設(shè)計(jì)和實(shí)現(xiàn)思路詳解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-07-07
C++實(shí)現(xiàn)字符串和整數(shù)的相互轉(zhuǎn)換
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)字符串和整數(shù)的相互轉(zhuǎn)換的方法,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C++有一定的幫助,需要的可以參考一下2023-01-01
C語言中字符串與各數(shù)值類型之間的轉(zhuǎn)換方法
這篇文章主要介紹了C語言中字符串與各數(shù)值類型之間的轉(zhuǎn)換方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
C++實(shí)現(xiàn)LeetCode(46.全排列)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(46.全排列),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07

