How to create a custom std::ostream which has an override for each primitive type

97 Views Asked by At

I am creating a custom logger that I want to use as a drop-in replacement for a std::ostream. I want to have overrides for each primitive type -- I do not want to implement a char-based streambuf thing (as you can see, I write to std::cerr anyway for now).

I'm getting a segfault with the following... I am not sure why. I've tried running in the debugger but even when I single-step through things, it's not clearly showing me why the segfault is occurring.

#include <iostream>

// A custom basic_ostream that has an implementation for each primitive type
struct Log : std::basic_ostream<char>
{
    Log& operator<<(int o) noexcept { std::cerr << "INT\n"; return *this; }
};

// I want my objects to keep using std::ostream
struct A
{
    friend std::ostream& operator<<(std::ostream& os, A const& o) noexcept
    {
        return os << o.x;
    }

private:
    int x;
};

int main()
{
    Log log;
    A a;
    log << a;
}
0

There are 0 best solutions below