C++ 字符格式化输出

文章目录

一、简介

这里使用std标准库简单实现一个字符格式化输出,方便后续的使用,它有点类似Qt中的QString操作。

二、实现代码

FMTString.hpp

cpp 复制代码
#pragma once

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <optional>
#include <random>
#include <type_traits>
#include <sstream>

namespace FMT 
{
    void formatStream(std::stringstream& stream, char const* text) {
        stream << text;
        return;
    }

    /// <summary>
    /// 在编译时检测某个类型T是否支持通过 operator<< 输出到流(如std::stringstream)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    template <class T>
    class IsStreamable {
    private:
        template <class TT>
        static auto test(int)
            -> decltype(std::declval<std::stringstream&>() << std::declval<TT>(),
                std::true_type());

        template <class>
        static auto test(...)->std::false_type;

    public:
        static bool const value = decltype(test<T>(0))::value;
    };

    /// <summary>
    /// 将任意类型的参数通过流操作符 << 转换为字符串流(std::stringstream)的内容
    /// </summary>
    /// <typeparam name="T"></typeparam>
    template <class T>
    class ArgToStream {
    public:
        static void impl(std::stringstream& stream, T&& arg) {
            stream << std::forward<T>(arg);
        }
    };

    /// <summary>
    /// 将格式字符串 text 中的 {} 占位符依次替换为传入的参数 arg, args...,并将结果写入 std::stringstream 流中
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="...Args"></typeparam>
    /// <param name="stream"></param>
    /// <param name="text"></param>
    /// <param name="arg"></param>
    /// <param name="...args"></param>
    template <class T, typename... Args>
    void formatStream(std::stringstream& stream, char const* text, T&& arg,
        Args&&... args) {
        static_assert(IsStreamable<T>::value,
            "One of the args has no ostream overload!");
        for (; *text != '\0'; ++text) {
            if (*text == '{' && *(text + 1) == '}') {
                ArgToStream<T&&>::impl(stream, std::forward<T>(arg));
                formatStream(stream, text + 2, std::forward<Args>(args)...);
                return;
            }
            stream << *text;
        }
        stream << "\nFormat-Warning: There are " << sizeof...(Args) + 1
            << " args unused.";
        return;
    }

    template <class... Args>
    std::string formatString(char const* text, Args&&... args) {
        std::stringstream stream;
        formatStream(stream, text, std::forward<Args>(args)...);
        return stream.str();
    }
}

main.cpp

cpp 复制代码
// 标准文件
#include <iostream>
#include <string>

#include "FMTString.hpp"

int main(int, char** argv)
{
    std::string msg = FMT::formatString("Hello, {}! You have {} new messages.", "Alice", 5);
    std::cout << "Output:" << msg << std::endl;

    system("pause");
    return 0;
}

三、实现效果

相关推荐
郭涤生6 小时前
布隆过滤器
c++
智者知已应修善业6 小时前
【求中位数】2024-1-23
c语言·c++·经验分享·笔记·算法
9ilk6 小时前
【C++】--- 特殊类设计
开发语言·c++·后端
程序员zgh10 小时前
Linux系统常用命令集合
linux·运维·服务器·c语言·开发语言·c++
獭.獭.10 小时前
C++ -- STL【unordered_set与unordered_map的实现】
开发语言·c++·unordered_map·unordered_set
qq_4335545410 小时前
C++数位DP
c++·算法·图论
似水এ᭄往昔11 小时前
【C++】--AVL树的认识和实现
开发语言·数据结构·c++·算法·stl
程序员zgh11 小时前
常用通信协议介绍(CAN、RS232、RS485、IIC、SPI、TCP/IP)
c语言·网络·c++
暗然而日章11 小时前
C++基础:Stanford CS106L学习笔记 8 继承
c++·笔记·学习
有点。11 小时前
C++ ⼀级 2023 年06 ⽉
开发语言·c++