C++ ToString

Content:

All Java/C#/Python/PHP developers know the toString/ToString/__str__/__toString methods that allows for easy conversion of custom classes to string in output.

C++ does not have such a magick method.

Since forever C++ developers has had the ability to add a << operator:

#include <iostream>
#include <string>

using namespace std;

class Data
{
private:
    int iv;
    string sv;
public:
    Data(int iv, string sv);
    friend ostream& operator<<(ostream& s, const Data& d);
};

Data::Data(int iv, string sv)
{
    this->iv = iv;
    this->sv = sv;
}

ostream& operator<<(ostream& s, const Data& d)
{
    s << "(" << d.iv << "," << d.sv << ")";
    return s;
}

int main()
{
    Data d(123, "ABC");
    cout << d << endl;
    return 0;
}

But C++ 20 has added a format/formatter framework.

In my best attempt to use it (partly based on a LinkedIn post):

#include <iostream>
#include <string>
#include <format>

using namespace std;

class Data
{
private:
    int iv;
    string sv;
public:
    Data(int iv, string sv);
    string ToString() const;
};

Data::Data(int iv, string sv)
{
    this->iv = iv;
    this->sv = sv;
}

string Data::ToString() const
{
    return format("({0},{1})", iv, sv);
}

template<>
struct std::formatter : std::formatter<string_view>
{
    format_context::iterator format(const Data& d, format_context& ctx) const
    {
        return format_to(ctx.out(), "{}", d.ToString());
    }
};

int main()
{
    Data d(123, "ABC");
    cout << format("{0}", d) << endl;
    return 0;
}

Well C++ is certainly getting more powerful. But it is not getting easier to learn.

Comments: