I need to create such an overloaded operator, which works only with predefined types (e.g. works with ofstream, stringstream, but doesn't work with ostream & iostream) . Here is an example:
// Possible usage: class Test : public BinaryTemplate - now you can simply write&read class Test from/to a file
class BinaryTemplate
{
public:
template <typename K>
// friend std::ostream& operator << (std::ostream&, K const&); // LINKER ERROR 2019
friend std::ios& operator << (std::ios&, K const&); // OK
}
template <typename Stream, typename K>
Stream& operator << (Stream& out, K const& c)
{
out.write(reinterpret_cast<const char*>(&c), sizeof(K));
out.flush();
return out;
}
BinaryTemplate bt;
cout << bt; // LINKER ERROR 2019 or OK
The compiler's behavior is very strange ( I hope it's clear for understanding
according to commented errors). When I declare friend method like <ios>
it's OK, because cout
object is instance of ostream
, which is derived from ios
. But when I declare friend method like <ostream>
it causes LINKER ERROR, but cout
object is instance of ostream
, then it is very strange for LINKER ERROR to be caused.
So, my question is:
Why Linker has such a behavior and how should I create class method, which works only with predefined types?
Thanks a lot