Problem with overriding "operator<<" in class derived from "ostream" - c++

I want to make a class based on "ostream" that does some auto-formatting to generate comma- or tab-separated-value files. My idea was to override "operator<<" to have it insert a separator before each value (except at the beginning and end of a line), and also to quote strings before writing them. Within the overriding "operator<<" method, I wanted to call the method of the base class, but I can't get it to work right.
Here's an example (compiles with g++ 4.3.3):
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
class MyStream: public ostream
{
public:
MyStream(ostream& out): ostream(out.rdbuf()) {}
template <typename T> MyStream& operator<<(T value)
{
ostream::operator<<('+');
ostream::operator<<(value);
ostream::operator<<('+');
return *this;
}
};
template<> MyStream& MyStream::operator<< <string>(string value)
{
ostream::operator<<('*');
ostream::write(value.c_str(), value.size()); // ostream::operator<<(value);
ostream::operator<<('*');
return *this;
}
int main()
{
MyStream mystr(cout);
mystr << 10;
cout << endl;
mystr << "foo";
cout << endl;
mystr << string("test");
cout << endl;
return 0;
}
The two "operator<<" methods (template and specialization) are there to handle strings differently than everything else. But:
The characters ('+'/'*') are printed as numbers and not characters.
The C-String "foo" prints as a memory address (I think).
If the "write" line is exchanged with the commented part, the compiler complains that there's "no matching function for call to 'MyStream::operator<<(std::string&)'", even though I thought I was explicitly calling the base class method.
What am I doing wrong? Any help greatly appreciated.

The operator<< overloads that prints strings and characters are free functions. But as you force calling member functions, you will force them to convert to one candidate of the member functions declared in ostream. For '*', it will probably use the int overload, and for "foo", it will probably use the const void* overload.
I would not inherit ostream, but instead store the ostream as a reference member, and then delegate from your operator<< to it. I would also not make operator<< a member, but rather a free function template, and not specialize but overload the operator<< for both std::string and char const*.

Something like the following might work:
include
#include <ostream>
#include <string>
using namespace std;
class MyStream: public ostream
{
public:
MyStream(ostream& out): ostream(out.rdbuf()) {}
template <typename T> MyStream& operator<<(const T& value)
{
(ostream&)*this << '+' << value << '+';
return *this;
}
MyStream& operator<< (const string& value)
{
(ostream&)*this << '*' << value << '*';
return *this;
}
MyStream& operator<< (const char* cstr)
{
(ostream&)*this << '(' << cstr << ')';
return *this;
}
};

Related

c++ get stream modifier from << overload

I have overloaded the stream insertion operator like this :
template<class Ch, class Tr, class word_type>
std::basic_ostream<Ch, Tr>&
operator << (std::basic_ostream<Ch, Tr>& s, const Mabit::mabit<word_type>& obj)
{
s << obj.to_string(Mabit::DEC, ',');
return s;
}
(mabit being the class for which i wanted the overload to work)
That is, since i can give different argument to the to_string method, i would like to be able to use standard stream modifier like std::dec, std::hex ... in a way that i could retrieve them from the overloaded operator to prepare the good argument as parameter for to_string
If i could also get the locale being used (to extract the separator for thousands) , it would be helpfull for the second argument too...
Is that possible ?
You can use std::basic_ostream::flags() to identify whether an format specifier was used.
http://en.cppreference.com/w/cpp/io/ios_base/flags
From http://www.cplusplus.com/reference/locale/numpunct/thousands_sep/
#include <iostream>
#include <locale>
using namespace std;
int main ()
{
int q=10977;
char separator = use_facet<numpunct<char> >(cout.getloc()).thousands_sep ();
cout << q/1000 << separator << q%1000 << endl;
return 0;
}
I suppose you can just replace cout with your stream argument in this example

Error: No operator << matches these operands?

I was practicing some c++ (trying to leave Java), and I stumbled on this annoying error saying:Error: No operater << matches these operands. I've searched this website for a clear answer and no luck, I did find that I'm not the only one.
This error is in my .cpp file, there are other errors, but I'm not paying any mind to them right now.
void NamedStorm::displayOutput(NamedStorm storm[]){
for(int i = 0; i < sizeof(storm); i++){
cout << storm[i] << "\n";
}
}
Something is up with the "<<" im not sure whats going on.
Since you are trying cout a class object you need to overload <<
std::ostream& operator<<(ostream& out, const NamedStorm& namedStorm)
You must overload the << operator in order to redirect your object into a stream.
You can overload as a member function, but in this case you must use the syntax object << stream in order to use that overloaded function.
If you wish to use this syntax stream << object then you must overload the << operator as a 'free' function, that is, not a member of your NamedStorm class.
Here is a working example:
#include <string>
#include <iostream>
class NamedStorm
{
public:
NamedStorm(std::string name)
{
this->name = name;
}
std::ostream& operator<< (std::ostream& out) const
{
// note the stream << object syntax here
return out << name;
}
private:
std::string name;
};
std::ostream& operator<< (std::ostream& out, const NamedStorm& ns)
{
// note the (backwards feeling) object << stream syntax here
return ns << out;
}
int main(void)
{
NamedStorm ns("storm Alpha");
// redirect the object to the stream using expected/natural syntax
std::cout << ns << std::endl;
// you can also redirect using the << method of NamedStorm directly
ns << std::cout << std::endl;
return 0;
}
The function which is called from the free redirection overload must be a public method of NamedStorm (in this case we are calling the operator<< method of the NamedStorm class), OR the redirection overload must be a friend of the NamedStorm class in order to access private fields.

Using ofstream* wrapper class with overloaded << operator on endl

C++
This is an attempt to make a class that mimics the output behavior of using the << operator of an ofstream, as far as being able to use std::endl and write strings is concerned. The class has a single data member, the ofstream pointer. The class has two overloaded << operators, one that takes an std::string and another that takes a pointer to a function, whose argument is an ostream reference and returns an ostream reference. That is the signature of std::endl, according to this. Technically, the below program works with the given input. It is able to print to file, two lines of text separated by two std::endls. However, I want my non-string parameter overloaded << operator to accept std::endl only, not something that merely matches its signature. I tried various combinations of placing std::endlin the argument list, with and without * and with and without &, but I got compiler errors for every combination. C++11 answers are also welcome.
#include <fstream>
#include <iostream>
#include <string>
class TextOut
{
public:
TextOut(std::ofstream* ofsPar) : ofs(ofsPar) {}
TextOut& operator<<(std::string s)
{
*ofs << s;
return *this;
}
TextOut& operator<<(std::ostream& (*endlPar) (std::ostream& os))
{
*ofs << std::endl;
return *this;
}
private:
std::ofstream* ofs;
};
int main()
{
std::cout << "Enter filename: ";
std::string filename;
std::cin >> filename;
std::ofstream myofstream(filename.c_str());
TextOut myTextOut(&myofstream);
myTextOut << "Hello," << std::endl << std::endl << "spacious world.";
return 0;
}
Output:
Hello,
spacious world.
If I look at my ostream header file I see this for endl:
template<typename _CharT, typename _Traits> inline basic_ostream<_CharT, _Traits>&
endl(basic_ostream<_CharT, _Traits>& __os)
{
return flush(__os.put(__os.widen('\n')));
}
so it looks like you would need to inherit from basic_ostream to make this work. Not sure you really want to do that.
As far as I know there is no way to enforce a parameter to be a specific value at compile time.
If compile-time enforcement is not a requirement, you could use a simple assert like this to enforce that the parameter is std::endl:
assert(static_cast<std::ostream& (*) (std::ostream& os)>(&std::endl) == endlPar);

How to define a static operator<<?

Is it possible to define a static insertion operator which operates on the static members of a class only? Something like:
class MyClass
{
public:
static std::string msg;
static MyClass& operator<< (const std::string& token) {
msg.append(token);
return *this; // error, static
}
};
alternatively:
static MyClass& operator<< (MyClass&, const std::string &token)
{
MyClass::msg.append(token);
return ?;
}
This is how I would like to use it:
MyClass << "message1" << "message2";
Thank you!
What I would probably do in your situation, is create another class that overloads the operator<<, then make a static member of that type. Like this:
class MyClass
{
public:
static std::string msg;
struct Out {
Out & operator<< (const std::string& token) {
MyClass::msg.append(token);
return *this;
}
};
static Out out;
};
Using it is not quite what you asked for, but close enough I think:
MyClass::out << "message1" << "message2";
If all the members of MyClass are static, it's possible to return a fresh instance.
However, returning a reference poses a problem. There are two solutions:
define a static instance
pass by copy, and not by reference.
The second approach is easiest:
static MyClass operator<< (MyClass, const std::string &token)
{
MyClass::msg.append(token);
return MyClass();
}
The first is one line more:
static MyClass& operator<< (MyClass&, const std::string &token)
{
static MyClass instance;
MyClass::msg.append(token);
return instance;
}
Usage is very close to what you want:
MyClass() << "message1" << "message2";
However, I would not recommend to do this. Why don't you just just use a std::ostringstream? You'll get formatting and some more for free. If you really need global access, declare a global variable.
If you want to use your class as cout, what you can do is example
#include <iostream>
using namespace std;
namespace trace
{
class trace
{
public:
trace& operator<< (const std::string& echo)
{
std::cout << echo << std::endl;
return *this;
}
};
trace t; // Note that we created variable so we could use it.
};
using namespace trace; // Note that we use same namespace so we dont need to do trace::t
int main(int argv, char** argc)
{
t << "Server started..."
<< "To exit press CTRL + Z";
return 0;
}
Output should look like each string in new line like this:
Server started...
To exit press CTRL + Z
You can't. A class-name / type is not a value in itself, you would need an expression like
class Foobar {...};
std::cout << Foobar << std::endl;
so that your static operator<< would be usable, but that is not valid C++. The grammar summary at A.4 shows that putting a type's name there is not valid.
Consider also that operator overloads are just functions with flaky names:
T operator<< (T, T)
^^^^^^^^^^ flaky name, basically same as:
T left_shift (T, T)
And functions in C++ (and most other languages, e.g. C#) can only work on instances of types, not types themselves.
However, C++ offers templates which have type arguments, howhowever, that would not help you to overload functions upon types.

Ambiguous operator <<

#include "stdafx.h"
#include "Record.h"
template<class T>//If I make instead of template regular fnc this compiles
//otherwise I'm getting an error (listed on the very bottom) saying
// that operator << is ambiguous, WHY?
ostream& operator<<(ostream& out, const T& obj)
{
out << "Price: "
<< (obj.getPrice()) << '\t'//this line causes this error
<< "Count: "
<< obj.getCount()
<< '\n';
return out;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<Record> v;
v.reserve(10);
for (int i = 0; i < 10; ++i)
{
v.push_back(Record(rand()%(10 - 0)));
}
copy(v.begin(),v.end(),ostream_iterator<Record>(cout, "\n"));
return 0;
}
//Record class
class Record
{
private:
int myPrice_;
int myCount_;
static int TOTAL_;
public:
Record(){}
Record(int price):myPrice_(price),myCount_(++TOTAL_)
{/*Empty*/}
int getPrice()const
{
return myPrice_;
}
int getCount()const
{
return myCount_;
}
bool operator<(const Record& right)
{
return (myPrice_ < right.myPrice_) && (myCount_ < right.myCount_);
}
};
int Record::TOTAL_ = 0;
Error 2 error C2593: 'operator <<' is ambiguous
The concept behind operator<<( ostream &, ... ) is that every class can have its own overload, handling that specific class in a way that make sense.
That means you get operator<<( ostream &, const Record & ) which handles Record objects, and operator<<( ostream &, const std::string & ) which handles standard strings, and operator<<( ostream &, const FooClass & ) which handles FooClass objects. Each of these functions knows how to handle the object type it has been declared for, because each of them requires a different handling. (E.g. getPrice() / getCount() for Record, or getFoo() / getBar() for FooClass.)
Your template is trampling roughshod over the whole concept. By defining it as a template function (which would match any class), you not only collide with the many definitions of operator<<() already in the standard / your codebase, but all possible overloadings.
How could the compiler decide whether to use operator<<( ostream &, const std::string & ) or your template? It cannot, so it throws up its hands in despair and gives up. That's what the error is telling you.
First, you need to read the error message more carefully. As an alternative, consider breaking the statement up, something like this:
out << "Price: ";
out << (obj.getPrice());
out << "\tCount: ";
out << obj.getCount();
out << '\n';
When you do, you'll realize that what's really causing the problem is not where you try to print out getPrice(), but where you try to print out "Price: ".
The problem is arising because the compiler doesn't know whether to use the normal overload to print out the string, or to use the template being defined to print it out. The latter would cause infinite recursion, and it couldn't actually compile since it requires an object on which you can/could call getPrice and getCount to compile correctly -- but it has a signature that matches, so the compiler says it's ambiguous, and that's the end of that.
The reason of the error is that your templated overload is conflicting with another templated overload, and there is no reason to prefer one template to another:
template<class charT, class traits>
basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>&, const charT*);
template <class T>
basic_ostream<char, char_traits<char> >& operator<< (basic_ostream<char, char_traits<char> >&, const T&);
//which one is preferable when you ask for: cout << "literal";?
(ostream should be a typedef for basic_ostream<char, char_traits<char> >.)
The whole idea of making your overload a template is questionable, seeing that the overload clearly cannot handle any other class than your Record.
There probably are techniques to allow you to provide a single templated overload for a number of unrelated Record-like classes with a little template metaprogramming (enable_if and traits), if that is the idea.