天天看點

C++中 std::string的format()函數實作

#include<string>
#include <iostream>
#include <memory>
using namespace std;

template< typename... Args >
std::string string_format(const char* format, Args... args)
{
    size_t length = std::snprintf(nullptr, 0, format, args...);
    if (length <= 0)
    {
        return "";
    }

    char* buf = new char[length + 1];
    std::snprintf(buf, length + 1, format, args...);

    std::string str(buf);
    delete[] buf;
    return std::move(str);
}

void main()
{
    cout << string_format("we have %d people",100) << endl;
    cout << string_format("we have %s people", "200") << endl;
}
           
C++中 std::string的format()函數實作

繼續閱讀