An example of overloading operator << in C++

The code below is compiled successfully with both GCC and MSVC:

#include <iostream>
#include <sstream>

template <class C>
class basic_format
{
public:
    
    template <typename T>
    basic_format & operator << (const T & val)
    {
        out << val;
        return *this;
    }

    std::basic_string<C> str() const { return out.str(); }

    operator std::basic_string<C>() const { return str(); }

private:
    
    std::basic_ostringstream<C> out;
};
using aformat = basic_format<char>;
using wformat = basic_format<wchar_t>;

class A {};

template <class C>
std::basic_ostream<C>& operator << (std::basic_ostream<C>& out, const A&)
{
    return out << static_cast<C>('A');
}

int main()
{
    A a;
    
    const std::string val = aformat() << a;

    std::cout << val << std::endl;
    
    return 0;
}

Compiling with GCC:

g++ -std=c++20 -pthread a.cpp -o a

Compiling with MSVC:

cl /std:c++20 /EHsc a.cpp

Leave a Reply

Your email address will not be published. Required fields are marked *