280

I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2 ) however I have the same problem on a Ubuntu system with the same g++.

Here is the relevant part of my matrix class:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
    }
}

And the "implementation":

using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

    [...]

}

This is the error given by the compiler:

matrix.cpp:459: error: 'std::ostream& Math::Matrix::operator<<(std::ostream&, const Math::Matrix&)' must take exactly one argument

I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)

Agnel Kurian
  • 57,975
  • 43
  • 146
  • 217
Matthias van der Vlies
  • 3,834
  • 3
  • 24
  • 28

6 Answers6

157

Just telling you about one other possibility: I like using friend definitions for that:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
            [...]
        }
    };
}

The function will be automatically targeted into the surrounding namespace Math (even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
145

You have declared your function as friend. It's not a member of the class. You should remove Matrix:: from the implementation. friend means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for Matrix class which is wrong.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 9
    And you should also declare it inside the Math namespace (not just with an using namespace Math). – David Rodríguez - dribeas Mar 23 '09 at 21:35
  • 1
    Why does the `operator<<` have to be in the namespace of `Math`? It seems that it should be in the global namespace. I agree that my compiler wants it to be in the namespace of `Math`, but that doesn't make sense to me. – Mark Lakata May 01 '15 at 21:58
  • Sorry, but I fail to see why do we use friend keyword here then? When declare friend operator override in a class, it seems like we cannot implement with Matrix::operator<<(ostream& os, const Matrix& m). Instead we need to just use global operator override operator< – Patrick Aug 02 '19 at 16:59
  • Patrick, You would use `friend` so that the implementation has access to private (and protected) member variables. E.g. It's likely you would want to print all the elements of the matrix, which may be private. – Erik Oct 14 '22 at 09:07
92

To add to Mehrdad answer ,

namespace Math
{
    class Matrix
    {
       public:

       [...]


    }   
    std::ostream& operator<< (std::ostream& stream, const Math::Matrix& matrix);
}

In your implementation

std::ostream& operator<<(std::ostream& stream, 
                     const Math::Matrix& matrix) {
    matrix.print(stream); //assuming you define print for matrix 
    return stream;
 }
kal
  • 28,545
  • 49
  • 129
  • 149
  • 4
    I don't understand why is this a down vote, this clarifies that you can declare operator to be in the namespace and not even as a friend and how you can possibly declare the operator. – kal Jan 24 '09 at 20:28
  • 2
    Mehrdad answer did not have any snippet of code so I just added what might work by moving it outside the class in the namespace itself. – kal Jan 24 '09 at 20:30
  • I understand your point, I only looked at your second snippet. But now I see you took the operator out of the class. Thanks for the suggestion. – Matthias van der Vlies Jan 24 '09 at 20:32
  • 7
    Not only it is out of the class, but it is properly defined _inside_ the Math namespace. Also it has the added advantage (maybe not for a Matrix, but with other classes) that 'print' can be virtual and thus printing will happen at the most derived level of inheritance. – David Rodríguez - dribeas Mar 23 '09 at 21:45
80

Assuming that we're talking about overloading operator << for all classes derived from std::ostream to handle the Matrix class (and not overloading << for Matrix class), it makes more sense to declare the overload function outside the Math namespace in the header.

Use a friend function only if the functionality cannot be achieved via the public interfaces.

Matrix.h

namespace Math { 
    class Matrix { 
        //...
    };  
}
std::ostream& operator<<(std::ostream&, const Math::Matrix&);

Note that the operator overload is declared outside the namespace.

Matrix.cpp

using namespace Math;
using namespace std;

ostream& operator<< (ostream& os, const Matrix& obj) {
    os << obj.getXYZ() << obj.getABC() << '\n';
    return os;
}

On the other hand, if your overload function does need to be made a friend i.e. needs access to private and protected members.

Math.h

namespace Math {
    class Matrix {
        public:
            friend std::ostream& operator<<(std::ostream&, const Matrix&);
    };
}

You need to enclose the function definition with a namespace block instead of just using namespace Math;.

Matrix.cpp

using namespace Math;
using namespace std;

namespace Math {
    ostream& operator<<(ostream& os, const Matrix& obj) {
        os << obj.XYZ << obj.ABC << '\n';
        return os;
    }                 
}
Dev Null
  • 4,731
  • 1
  • 30
  • 46
sanjivr
  • 991
  • 8
  • 12
  • 1
    Just a little nitpicking here.. i find `os` to be a poor abbreviation in this case (it is bound too much to "operating system") – LeonTheProfessional Jul 09 '20 at 08:47
  • Can the `operator<<` overload be put (declared and implemented) inside the class, and we don't talk about friendship? – KcFnMi Oct 07 '22 at 03:16
49

In C++14 you can use the following template to print any object which has a T::print(std::ostream&)const; member.

template<class T>
auto operator<<(std::ostream& os, T const & t) -> decltype(t.print(os), os) 
{ 
    t.print(os); 
    return os; 
} 

In C++20 Concepts can be used.

template<typename T>
concept Printable = requires(std::ostream& os, T const & t) {
    { t.print(os) };
};

template<Printable T>
std::ostream& operator<<(std::ostream& os, const T& t) { 
    t.print(os); 
    return os; 
} 
QuentinUK
  • 2,997
  • 21
  • 20
  • interesting solution! One question - where this operator should be declared, like in a global scope? I assume it should be visible to all types which can be used to templatize it? – barney May 16 '16 at 06:08
  • @barney It could be in your own namespace along with the classes that use it. – QuentinUK May 16 '16 at 23:30
  • can't you just return `std::ostream&`, since it's the return type anyway ? – Jean-Michaël Celerier Mar 08 '17 at 20:16
  • 7
    @Jean-MichaëlCelerier The decltype makes sure that this operator is only used when t::print is present. Otherwise it would attempt to compile the function body and give a compilation error. – QuentinUK Mar 12 '17 at 10:43
  • Concepts version added, tested here https://godbolt.org/z/u9fGbK – QuentinUK May 04 '20 at 13:34
4

I would like to simplify this a little with an example that overloads << to print an array.

  1. First pass both the object types around the << operator
  2. create a function to overload the operator as follows.
#include<iostream> 
using namespace std;

void operator<<(ostream& os, int arr[]) {
    for (int i = 0;i < 10;i++) {
        os << arr[i] << " ";
    }
    os << endl; 
}
    
int main() {
    int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
    cout << arr;
}

if cascading of operators is also required make sure to return cout object in the overloaded function as follows,

#include<iostream> 
using namespace std;

ostream& operator<<(ostream& os, int arr[]) {
    for (int i = 0;i < 10;i++) {
        cout << arr[i] << " ";
    }
    cout << endl; 
    return os;
}
    
int main() {
    int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
    int arr2[10] = { 11,22,33,44,55,66,77,88,99,100 };
    // cascading of operators
    cout << arr << arr2;
}
mcleod_ideafix
  • 11,128
  • 2
  • 24
  • 32
Hemanth Kollipara
  • 902
  • 11
  • 16