Why doesn`t operator<< work successfully? - c++

While compiling the below code, I am getting an error:
Expression.h
class Expression{
...
protected:
std::ostream Os;
};
Expression.c
Expression::Expression() : Os(std::cout)
{
...
}
Expression::Expression(std::ofstream &os) : Os(os)
{
...
}
Expression::Dump()
{
Os << "=============================================================" << std::endl;
Os << "Os: " << Os << std::endl;
}
error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'std::ostream {aka std::basic_ostream<char>}')
What is my mistake? What should I do to fix it?
And while giving initial value to parameter like this Os(std::cout), what does it mean?

Consider
Os << "Os: " << Os << std::endl;
Let us unpack it into its full functional glory:
std::ostream& t1 = Os.operator <<("Os: ");
std::ostream& t2 = t1.operator <<(Os); // << Here
std::ostream& t3 = t2.operator <<(std::endl);
The problem is the line marked "Here". You are streaming an ostream to itself. This is nonsensical. What are you trying to do?
If you are trying to output an identifier for the stream, you should use the address:
Os << "Os: " << &Os << std::endl;
If you are trying to output the contents of the stream to stdout, you need to make Os be an ostringstream, and then output the string buffer:
std::ostringstream Os;
...
std::stdout << "Os: " << Os.str() << std::endl;
Note for the pedantic: I believe my breakdown of the original line into function calls and initializations is actually identical in this particular case (because there are no temporary objects - only references); in general, the lifetime of temporaries might be subtly different.

The error is because there is no standard operator<< that writes an ostream to another ostream.
Also, ostream can't be copy-constructed from another ostream, so if you are trying to specify an output ostream for Expression to write to then your Os member needs to be declared as a reference instead.
class Expression {
...
protected:
std::ostream &Os;
};
Expression::Expression() : Os(std::cout)
{
...
}
Expression::Expression(std::ofstream &os) : Os(os)
{
...
}
Expression::Dump()
{
Os << "=============================================================" << std::endl;
Os << "Os: " << SomethingThatIsNotOs << std::endl;
}

Related

how to print the content of a c++ function argument given such information

I have a c++11 code which has a function like the following:
bool prepareSwitch(const std::list<hardware_interface::ControllerInfo>& start_list,
const std::list<hardware_interface::ControllerInfo>& stop_list)
for debugging this code, I'd like to investigate/print for example the start_list, however, having a quite basic experience in c++ has made this confusing for me. Yet, the additional information that I can have about this input argument is about <hardware_interface::ControllerInfo> the described in this documentation.
I'm not sure how to use this information to print or investigate this input. Can someone guide a little about it?
using std::cout << start_list << std::endl; gave a compilation error.
To ease debugging you can overload the following operators. (adapt the formatting as needed)
std::ostream & operator<<(std::ostream & os, const hardware_interface::InterfaceResources &ir)
{
os << "hi: " << ir.hardware_interface << std::endl;
for (const auto & r : ir.resources)
{
os << "r: "<< r << std:;endl;
}
return os
}
std::ostream & operator<<(std::ostream & os, const hardware_interface::ControllerInfo &ci)
{
os << "name:" << ci.name << std::endl;
os << "type: " << ci.type<< std::endl;
for (const auto & cr : ci.claimed_resources)
{
os << "cr: " << cr << std::endl;
}
return os
}
Then you can print your functions arguments:
for (const auto& ci: startList)
{
std::cout << ci;
}

Overloading the ostream operator yields compile errors

Hi all I have this code -
typedef struct signal_declairation{
//these are for 2001 type declairation
bool is_array;
int array_start, array_end;
PORT_ATTRIBUTE port_attribute; //port direction
string port_type; //logic, UDT, wire, accept every thing
//this is common to 2001 and normal
string port_name;
//dumper method
friend ostream& operator<<(ostream &out, signal_declairation &m_signal_declairation);
} SIGNAL_DECLAIRATION;
std::ostream& operator<< (ostream &out, signal_declairation &m_signal_declairation)
{
string port_direction;
switch(m_signal_declairation.port_attribute){
case INPUT: port_direction = "input";
break;
case OUTPUT: port_direction = "output";
break;
case INOUT: port_direction = "inout";
break;
}
if(m_signal_declairation.is_array==true){
out << " Port Name = " << m_signal_declairation.port_name
<< " Port Direction = " << m_signal_declairation.port_attribute
<< " Port type = " << m_signal_declairation.port_type
<< " This is an arrayed port :: Array Start = " << m_signal_declairation.array_start
<< " Array End = " << m_signal_declairation.array_end ;
}else{
out << " Port Name = " << m_signal_declairation.port_name
<< " Port Direction = " << m_signal_declairation.port_attribute
<< " Port type = " << m_signal_declairation.port_type;
}
return out;
}
When I try and compile, I get errors that look like this -
parser_globals.h: In function ‘std::ostream& operator<<(std::ostream&,
signal_declairation&)’: parser_globals.h:53:9: error: no match for
‘operator<<’ (operand types are ‘std::ostream {aka
std::basic_ostream}’ and ‘const char [14]’)
out << " Port Name = " << m_signal_declairation.port_name
Not sure why I am not able to pass class members to << as shown above. Can anyone help ????
Thanks
Raj
If you had provided the complete error messages that you get and not just a small snippet, things would have been easier.
Based on what you provided so far, it looks like you might have forgot to include the necessary header(s) for the standard streams, e.g.:
#include <iostream>
This would cause the compiler to not find the operator<< overloads for the base types or the types from the standard library.
change your overload definition :
std::ostream& operator<< (ostream &out, signal_declairation &m_signal_declairation)
by std::ostream& operator<< (ostream &out,const signal_declairation &m_signal_declairation) .
Dont forget the prototype too.
The compiler complains about the ‘const char [14]’) out << " Port Name = ". It looks like the compiler cannot see the " Port Name - " as string, rather it sees it as character array. Have you include ?

How to iterate a map of string and structure in C++?

I am trying to iterate the below map and prints out everything in C++.
struct employee
{
uint16_t id;
uint8_t lastModifiedDate[8];
std::string value;
};
std::map<std::string, employee> m1;
As you can see the above map is of type key string and value as employee...
Below is try I have given but somehow whenever I compile the above code, I get bunch of exceptions at my console.. I am not sure which error will make sense to copy paste it here... So that's why I am not pasting it here for now.. If somebody needs it, I can make it small and then copy it here..
std:map<std::string, employee>::const_iterator itMap = m1.begin();
for (;itMap !=m1.end(); ++itMap) {
std::cout << itMap->first << " : " << itMap->second << std::endl;
}
std::cout << std::endl;
Any idea what wrong I am doing here?
Update:-
This is the error message I am seeing -
error: no match for operator<< in std::operator<<
>((* & std::operator<< , std::allocator >((* & std::cout), (* &
itMap.std::_Rb_tree_const_iterator<_Tp>::operator->, employee> >()->std::pair, employee>::first))), ((const char*)" : ")) <<
itMap.std::_Rb_tree_const_iterator<_Tp>::operator->, employee> >()->std::pair, employee>::second
std::cout won't know how to print your employee until you override operator<< for employee type. Like this:
std::ostream& operator<<(std::ostream& os, const employee& e)
{
os << e.id << lastModifiedDate[0] << value;
rteurn os;
}
You need to specify which member of the employee that you want to output to cout
std:map<std::string, employee>::const_iterator itMap = m1.begin();
for (;itMap !=m1.end(); ++itMap) {
std::cout << itMap->first << " : " << itMap->second.value << std::endl;
// ^^^^^^
}
std::cout << std::endl;

Compiler error message with cout

I mistyped the error message before. It is fixed now.
I'm currently getting the following compiler error message
error: no match for 'operator<<' in 'std::cout << Collection::operator[](int)(j)'
The code that the compiler is complaining about is
cout << testingSet[j];
Where testingSet is an object of type Collection that has operator[] overloaded to return an object of type Example. Example has a friend function that overloads operator<< for ostream and Example.
note: this actually compiles just fine within Visual Studio; however does not compile using g++.
Here is the implementation of operator<<:
ostream& operator<<(ostream &strm, Example &ex)
{
strm << endl << endl;
strm << "{ ";
map<string, string>::iterator attrib;
for(attrib = ex.attributes.begin(); attrib != ex.attributes.end(); ++attrib)
{
strm << "(" << attrib->first << " = " << attrib->second << "), ";
}
return strm << "} classification = " << (ex.classification ? "true" : "false") << endl;
}
And the operator[]
Example Collection::operator[](int i)
{
return examples[i];
}
Probably your operator should be declared as:
ostream& operator<<(ostream &strm, const Example &ex)
Note the const-reference to Example.
Visual Studio has an extension that allows to bind a reference to a non-const r-value. My guess is that your operator[] returns an r-value.
Anyway, an operator<< should be const as it is not expected to modify the written object.

print time on each call to std::cout

How would someone do that?
for example I do like:
std::cout << "something";
then it should print the time before "something"
Make your own stream for that :) This should work:
class TimedStream {
public:
template<typename T>
TimedStream& operator<<(const T& t) {
std::cout << getSomeFormattedTimeAsString() << t << std::endl;
return *this;
}
};
TimedStream timed_cout;
void func() {
timed_cout << "123";
}
You'd be able to use this class for every type for which std::cout << obj can be done, so no further work is needed.
But please note that the time will be written before every <<, so you cannot chain them easily. Another solution with explicit timestamp is:
class TimestampDummy {} timestamp;
ostream& operator<<(ostream& o, TimestampDummy& t) {
o << yourFancyFormattedTimestamp();
}
void func() {
cout << timestamp << "123 " << 456 << endl;
}
You could use a simple function that prints the timestamp and then returns the stream for further printing:
std::ostream& tcout() {
// Todo: get a timestamp in the desired format
return std::cout << timestamp << ": ";
}
You would then call this function instead of using std::cout directly, whenever you want a timestamp inserted:
tcout() << "Hello" << std::endl;
ostream& printTimeWithString(ostream& out, const string& value)
{
out << currentTime() << ' ' << value << std::endl;
return out;
}
Generate current time using your favourite Boost.DateTime output format.
This looks like homework. You want something in the line of:
std::cout << time << "something";
Find a way the retrieve the time on your system, using a system call.
Then you'll have to implement a << operator for your system-dependent time class/struct.