So, I have a question in regards to an error I recently experienced when I tried to overload the << operator.
I have a file, called "structPixels.h" where in I define a struct as follows:
#pragma once
#include <iostream>
namespace Eng
{
/**
* A structure to represent pixels
*/
typedef struct Pixel{
unsigned int x; ///The x-coordinate
unsigned int y; ///The y-coordinate
bool operator ==(const Pixel& rhs) const
{
return (this->x == rhs.x && this->y == rhs.y);
};
bool operator !=(const Pixel& rhs) const
{
return (this->x != rhs.x || this->y != rhs.y);
};
bool operator <(const Pixel& rhs) const
{
return std::tie(this->x, this->y) < std::tie(rhs.x, rhs.y);
}
friend std::ostream& operator << (std::ostream& out, const Pixel& p);
} Pixel;
}//End of namespace Eng
namespace std {
//Removing the inline does not fix the error. Rather, it fixed another error
//which I had with duplicate symbols
inline ostream& operator<<(ostream &os, const Eng::Pixel &p)
{
os << "{"
<< p.x
<< ","
<< p.y
<< "}";
return os;
}
}//End of namespace std
However, when I create it and call a cout like so:
#include "structPixels.h"
Pixel test = {3, 4};
std::cout << "Test: " << test << std::endl;
I get that:
error: use of overloaded operator '<<' is ambiguous (with operand types 'basic_ostream<char, std::__1::char_traits<char> >' and 'Eng::Pixel')
std::cout << "Test: " << test << std::endl;
~~~~~~~~~~~~~~~~~~~~~ ^ ~~~~
EDIT: From the help below, we moved the operator, such that the code looks like so:
namespace Eng
{
/**
* A structure to represent pixels
*/
typedef struct Pixel{
unsigned int x; ///The x-coordinate
unsigned int y; ///The y-coordinate
bool operator ==(const Pixel& rhs) const
{
return (this->x == rhs.x && this->y == rhs.y);
};
bool operator !=(const Pixel& rhs) const
{
return (this->x != rhs.x || this->y != rhs.y);
};
bool operator <(const Pixel& rhs) const
{
return std::tie(this->x, this->y) < std::tie(rhs.x, rhs.y);
}
} Pixel;
inline std::ostream& operator<<(std::ostream& os, const Pixel& rhs)
{
os << "{" << rhs.x << "," << rhs.y << "}";
return os;
}
}//End of namespace Eng
This solved the error :)!