0

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.

Selvidian
  • 45
  • 7

1 Answers1

1

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:

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
  • Still this has me #include something in my matrix3x3 header. I'm trying to find an answer to the problem which does not require including anything and i believe what @user0042 proposed in the comments will do the trick. – Selvidian Nov 23 '17 at 19:39
  • @Selvidian: If you don't want to "`#include` something", then you are using the wrong language. `` is made for your use case. Use it. – Christian Hackl Nov 23 '17 at 19:41
  • @Selvidian: What @user0042 proposed accomplishes nothing (because `` does exactly the same thing) and possibly breaks something (because it's not allowed to forward-declare standard classes yourself). – Christian Hackl Nov 23 '17 at 19:44
  • Understood, it seems like my question has been answered. Thank you – Selvidian Nov 23 '17 at 19:46