Selvidian
Selvidian

Reputation: 45

Overloading Iostream C++

I'm writing a header only matrix3x3 implementation which I want to be independent and not relying on other headers except for a vector3 header which i also wrote.

Currently, I want it to overload ostream << operator but I don't want to include the iostream in it.

Is it possible to make the overloading optional and work if ostream is included, and if its not included to have all the rest work fine just without the overload?

I thought about the possibility of checking if the ostream header is included but it has a major flaw because it would not work correctly if iostream was included after the matrix3x3 header.

Edit: I've replaced iostream with ostream as i think it created a bit of confusion regarding the point of the question.

Upvotes: 0

Views: 181

Answers (1)

Christian Hackl
Christian Hackl

Reputation: 27538

Why not use <iosfwd>?

Example:

#include <iosfwd>

class Example
{
public:
    Example(int i) : i(i) {}
private:
    int i;
    friend std::ostream& operator<<(std::ostream& os, Example const& example);
};

#include <iostream>

int main()
{
    Example e(123);
    std::cout << e << '\n';
}

std::ostream& operator<<(std::ostream& os, Example const& example)
{
    os << example.i;
    return os;
}

Note that you cannot safely forward-declare standard classes in your own code. Related questions:

Upvotes: 1

Related Questions