Integer to string or wstring converter I can't use std::to_string and std::to_wstring function, so I have written a converter:

///@struct ParseInt
///Contains function that parses integer.
template&lt;typename Char_T&gt; struct ParseInt{
    static std::basic_string&lt;Char_T&gt; toString(int x);
};

///Converts integer to std::string
///@param x the integer to convert
///@return std::string from the integer
template&lt;&gt; inline std::string ParseInt&lt;char&gt;::toString(int x){
    int length = 2; //most ints coming here are 2 digits long.
    char* buf = 0;
    do{
        delete[] buf;
        buf = new char[++length + 1];
    }while(sprintf(buf, "%d", x) &lt; 0);
    std::string str(buf);
    delete[] buf;
    return str;
}


///Converts integer to std::wstring
///@param x the integer to convert
///@return std::wstring from the integer
template&lt;&gt; inline std::wstring ParseInt&lt;wchar_t&gt;::toString(int x){
    int length = 2; //most ints coming here are 2 digits long.
    wchar_t* buf = 0;
    do{
        delete[] buf;
        buf = new wchar_t[++length + 1];
    }while(swprintf(buf, length + 1, L"%d", x) &lt; 0);
    std::wstring str(buf);
    delete[] buf;
    return str;
}


I am not sure how efficient it is. Is there any solution that is more efficient?
I am not sure how efficient it is. Is there any solution that is more efficient?


Very inefficient.

First, you allocate buffers with new/delete. You should not do that. Second, you allocate in a loop. You shouldn't do that either.

Consider this code instead (function renamed to to_string, as what you do is not parsing - parsing would be the inverse operation - taking a string and extracting an integer from it):

auto print(char * buffer, int x)
{
    return sprintf(buffer, "%d", x);     
}

auto print(wchar_t * buffer, int x)
{
    return wsprintf(buffer, "%d", x);     
}

///Converts integer to std::string
///@param x the integer to convert
///@return std::string/std::wstring from the integer
template&lt;typename C,
    typename T=std::char_traits&lt;C&gt;,
    typename A=std::allocator&lt;C&gt;&gt;
std::basic_string&lt;C,T,A&gt; to_string(int x)
{
    C buffer[ 64 ] = { 0 }; // no new/delete required
                            // no loop required
                            // max int on 32bit architectures is
                            // 2,147,483,647; 64 bytes is "big enough"

    auto written = print(buffer, "%d", x);
    assert(written &gt; 0); // should always be true
    return std::basic_string&lt;C,T,A&gt;{ buffer, buffer + written };
}


Advantages:


there is no code repetition (easier to maintain)
efficiency is linear in to_string (no loops)
code is simpler and more straight-forward