C/C++ fmt 格式化字符串实现(轻量)

实现的目的;提高 C/C++ 编译速度,fmt 库模板嵌套过多编译速度非常慢,且编译后程序体积也过大,函数步入的栈帧过多!

只支持格式;{}

不支持格式;{:02x}

class fmt
{
public:
    template 
    static std::string              format(const S& fmt, T ... args) noexcept
    {
        std::string str;
        if constexpr (std::is_same::value)
        {
            str = fmt;
        }
        else if constexpr (std::is_same::value)
        {
            str = std::string(fmt.data(), fmt.size());
        }
        else
        {
            str = fmt;
        }

        (..., format_string(str, args));
        return str;
    }

    template 
    static void                     format_to(OutputIt&& out, const std::string& fmt, T ... args)
    {
        std::string result = format(fmt, std::forward(args)...);
        for (char ch : result)
        {
            *out = ch;
        }
    }

private:
    template 
    static std::string              to_string(const T& value) noexcept
    {
        if constexpr (std::is_same::value)
        {
            return value ? "true" : "false";
        }
        else if constexpr (std::is_pointer::value)
        {
            using DECAY_T = typename std::decay::type;

            if constexpr (std::is_same::value || std::is_same::value)
            {
                return value ? value : "";
            }
            else 
            {
                if (value)
                {
                    char buf[sizeof(value) << 2];
                    snprintf(buf, sizeof(buf), "%p", reinterpret_cast(value));
                    return buf;
                }
                return "null";
            }
        }
        else if constexpr (std::is_same::value)
        {
            return value;
        }
        else if constexpr (std::is_same::value)
        {
            return std::string(value.data(), value.size());
        }
        else
        {
            return std::to_string(value);
        }
    }

    template 
    static std::string              to_string(const std::shared_ptr& value) noexcept
    {
        return fmt::to_string(value.get());
    }

    template 
    static void                     format_string(std::string& out, const T& value) noexcept
    {
        replace_string(out, "{}"sv, fmt::to_string(value));
    }

public:
    static bool                     replace_string(std::string& str, const std::string_view& old_string, const std::string_view& new_string) noexcept;
};

inline bool fmt::replace_string(std::string& str, const std::string_view& old_string, const std::string_view& new_string) noexcept
{
    size_t pos = str.find(old_string);
    if (pos == std::string::npos)
    {
        return false;
    }

    str.replace(pos, old_string.length(), new_string);
    return true;
}

你可能感兴趣的:(C/C++,c语言,c++,java)