std::format 如何实现编译期格式检查

C++ 20 的 std::format 是一个很神奇、很实用的工具,最神奇的地方在于它能在编译期检查字符串的格式是否正确,而且不需要什么特殊的使用方法,只需要像使用普通函数那样传参即可。

cpp 复制代码
#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 需要为每个字符串字面量创建不同的类型才能实现编译期格式检查。fmt 提供了一个 FMT_STRING 宏以简化使用的流程。

cpp 复制代码
#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 函数与以前的 constexpr 函数不同,constexpr 函数只有在必须编译期求值的语境下才会在编译期执行函数,而 consteval 函数在任何情况下都强制编译期求值。std::format 就是利用 consteval 函数在编译期执行代码,来检查字符串参数的格式。

然而 std::format 自身不能是 consteval 函数,只好曲线救国,引入一个辅助类型 std::format_string,让字符串实参隐式转换为 std::format_string。只要这个转换函数是 consteval 函数,并且把格式检查的逻辑写在这个转换函数里面,照样能实现编译期的格式检查。

这里我们实现了一个极简版的 format,可以检查字符串中 {} 的数量是否与参数的个数相同。format_string 的构造函数就是我们需要的隐式转换函数,它是一个 consteval 函数。若字符串中 {} 的数量不对,则代码会执行到 throw 这一行。C++ 的 throw 语句不能在编译期求值,因此会引发编译错误,从而实现了在编译期检查出字符串的格式错误。

cpp 复制代码
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) {
        // 省略具体的格式化逻辑
    }
}

有一个细节,此处 format 函数的参数写的是 format_string<std::type_identity_t<Args>...>,直接写 format_string<Args ...> 是无法隐式转换的,因为模板实参推导 (template argument deduction) 不会考虑隐式转换,C++ 20 提供了一个工具 std::type_identity 可以解决这个问题。std::type_identity 其实就是一个关于类型的恒等函数,但是这么倒腾一下就能在模板实参推导中建立非推导语境 (non-deduced context),进而正常地匹配到隐式转换,C++ 就是这么奇怪。参考资料:c++ - why would type_identity make a difference? - Stack Overflow

相关推荐
C++ 老炮儿的技术栈27 分钟前
Linux 文件系统目录架构全解析
linux·服务器·c语言·开发语言·c++
样例过了就是过了37 分钟前
LeetCode热题100 分割回文串
数据结构·c++·算法·leetcode·深度优先·dfs
阿猿收手吧!1 小时前
【C++】高并发内存池架构与设计解析
开发语言·c++·架构
唠玖馆1 小时前
c++ 类和对象(全)
java·开发语言·c++
Morwit1 小时前
【力扣hot100】 85. 最大矩形
c++·算法·leetcode·职场和发展
m0_528174452 小时前
C++中的代理模式变体
开发语言·c++·算法
mjhcsp2 小时前
C++ 折半搜索(Meet in the Middle):突破指数级复杂度的分治策略
开发语言·c++
2401_883035462 小时前
C++代码风格检查工具
开发语言·c++·算法
witAI3 小时前
**Sora仿真人剧2025推荐,解锁沉浸式互动叙事新体验*
c++
CodeCraft Studio3 小时前
Parasoft C/C++嵌入式软件测试解决方案:安全、可靠且符合标准
开发语言·c++·安全·单元测试·代码规范·parasoft·嵌入式软件测试