c++格式化字符串的几种方式

方式一 纯c++方式(c++11)

#include <string>
#include <memory>

template <class... Args>
int string_format(std::string& format, Args&&... args)
{
    auto size_buf = std::snprintf(nullptr, 0, format.c_str(), std::forward<Args>(args)...) + 1;
    std::unique_ptr<char[]> buf = std::make_unique<char[]>(size_buf);
    if (!buf)
    {
        return 0;
    }

    std::snprintf(buf.get(), size_buf, format.c_str(), std::forward<Args>(args)...);
    format = std::string(buf.get(), buf.get() + size_buf - 1);
    return format.length();
}

int main()
{
    std::string str = "this is a num %d";
    int length = string_format(str, 20);
    return 0;
}

方式二 使用boost库

使用循环递归方式解析可变参数

#include <boost/format.hpp>

void str_format_helper(boost::format& fmt)
{
    //boost::str(fmt);
}

template <class T, class... Args>
void str_format_helper(boost::format& fmt, T&& head, Args&&... args)
{
    str_format_helper(fmt % std::forward<T>(head), std::forward<Args>(args)...);
}

template <class... Args>
std::string str_format(const std::string& format, Args&&... args)
{
    boost::format fmt(format);
    str_format_helper(fmt, std::forward<Args>(args)...);
    return fmt.str();
}
posted @ 2021-10-22 16:45  川野散人  阅读(1364)  评论(0)    收藏  举报