Quick Q: Why is there no to_string(const string&)?

Quick A: If you need such a function you can create it.

Recently on SO:

Why is there no to_string(const string&)?

You can just write your own templated function with proper overloads as follows:

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

template<typename T>
std::string toString(const T& t) {
    return std::to_string(t);
}

std::string toString(const char* t) {
    return t;
}

std::string toString(const std::string& t) {
    return t;
}

int main() {
    cout << toString(10) << endl;
    cout << toString(1.5) << endl;
    cout << toString("char*") << endl;
    cout << toString(std::string("string")) << endl;
    return 0;
}

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.