Sharry
Sharry

Reputation: 15

How to convert from any type to std::string in C++

I'm making a LinkedList class using template, since I want to use it for whatever type I need afterwards

template <typename T> class LinkedList {}

I'm trying to make a function that adds all the elements of a list into a string:

std::string join(const char *seperator)
{
    std::string str;
    auto curr = this->head;
    while (curr)
    {
        str += std::to_string(curr->value);
        if (curr->next)
            str += seperator;
        curr = curr->next;
    }
    return str;
}

It works with the types I tested (int, double, float...) but doesn't work with std::string, the to_string() function generates an error

Error C2665 'std::to_string': none of the 9 overloads could convert all the argument types

I assume it doesn't work with other types. so, can you provide a general method to convert from any type to std::string.

Upvotes: 0

Views: 2057

Answers (1)

Andrey Semashev
Andrey Semashev

Reputation: 10606

There is no universal way to convert an object of arbitrary type to a string in C++. But the most commonly supported facility for outputting data as strings are output streams. So, you could use std::ostringstream like this:

std::string join(const char *seperator)
{
    std::ostringstream strm;
    auto curr = this->head;
    while (curr)
    {
        strm << curr->value;
        if (curr->next)
            strm << seperator;
        curr = curr->next;
    }
    return strm.str();
}

Note that for this to work the type T should provide an operator<< overload that takes std::ostream& as the first argument. All arithmetic types, C-style strings and std::string are supported by this facility, but not all user-defined types may be.

Upvotes: 8

Related Questions