473,659 Members | 2,944 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

No match for operator<< when using std::endl

2 New Member
When compiling the below I get the following error:
no match for 'operator<<' in 'log << std::endl' main.cpp

Why can't I use std::endl in my class?

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. class Logger {
  4.         public:
  5.                 template <typename T>
  6.                 Logger& operator << (const T &t)
  7.                 {
  8.                     // do sth with t
  9.                     std::cout << t;
  10.                     return *this;
  11.                 }
  12. };
  13.  
  14. int main()
  15. {
  16. Logger log;
  17.  
  18. log << "Hello " << 10 << 20;  // ok
  19. log << std::endl; // fault here
  20.  
  21. }
  22.  
Mar 9 '10 #1
5 5717
weaknessforcats
9,208 Recognized Expert Moderator Expert
The operator<< cannot be a member function. This is because the first argument of the << function must be the object to the left of the operator and the second argument is the object to the right of the operator. LIke this:

Expand|Select|Wrap|Line Numbers
  1. ostream& operator<<(ostream& os, Logger& obj);
As a member function, the compiler will insert the this pointer of your Logger object as the first argument. That would be a pointer to a Logger object. std::endl requires an ostream& and not a Logger*.

The solution is to make your operator<< a friend function. It should have the prototype shown above.
Mar 9 '10 #2
JerryBrit
2 New Member
Thanks for quick reply weaknessforcats ,

but declaring the function this way:
friend ostream& operator<<(ostr eam& os, Logger& obj)
how can I pass parameters to the Logger class?
Mar 9 '10 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
You have Logger object right?

Expand|Select|Wrap|Line Numbers
  1. Logger obj( the parameters);
  2.  
  3. obj.SetFormat(parameters for formatting the log);
  4.  
  5. //etc...
  6.  
  7. cout << obj << endl;

The code above is a call to

Expand|Select|Wrap|Line Numbers
  1. ostream& operator<<(ostream&, Logger&);
followed by a call to

Expand|Select|Wrap|Line Numbers
  1. ostream& operator<<(ostream&, ostream& (*)(ostream&));
The second call is for the endl. The second function is provided by the C++ Library.

You could also:

Expand|Select|Wrap|Line Numbers
  1. cout << Logger(the parameters) << endl;

That would create a Logger object which would be used an then deleted when the satement was complete.
Mar 10 '10 #4
Banfa
9,065 Recognized Expert Moderator Expert
weaknessforcats my reading of what JerryBrit is trying to do (and I may be wrong) is that they are not trying to output the data in Logger but that the Logger class is an intercept to say log the output of a program as it is running and although it currently outputs to cout it might in future be altered to output to a file or to both cout and a file.

JerryBrit if my interpretation is wrong you should say because in that case what weaknessforcats is almost certainly right. However if I am right any data in the Logger class is irrelivent and is not being output anyway, Logger needs to receive data in the same way that cout normally does not be capable of being passed to cout.

I think, but listen to weaknessforcats because he really is the expert, that in that case what you would want is your own logging version of endl defined something like

Logger& loggerendl ( Logger& os );

to output an end of line to the log output. Or you would need to define a member function of Logger something like

Logger& Logger::operato r<<(ostream& ( *pf )(ostream&));

to accept stream manipulators like endl.
Mar 10 '10 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
You might try:

Expand|Select|Wrap|Line Numbers
  1. class Logger { 
  2. private:
  3.     ofstream theLog;
  4.            public: 
  5.             Logger();
  6.                 template <typename T> 
  7.                 Logger& operator << (const T &t) 
  8.                 { 
  9.                     // do sth with t 
  10.                     this->theLog << t; 
  11.                     return *this; 
  12.                 } 
  13.  
  14. }; 
  15. Logger::Logger(): theLog("TheLogFile.txt")
  16. {
  17.  
  18. }
  19.  
  20. int main() 
  21. Logger log; 
  22.  
  23. log << "Hello " << 10 << 20;  // ok 
  24. log << std::endl; // fault here 
Here I added an ofstream object to your Logger. This the log file. Since it is an ofstream and since ofstream is a kind-of ostream, then a manipulator like std::endl should work with an ofstream object.

Then all I did was add a Logger constructor to get the file name and change your Logger::operato r<< to use the ofstream member variable rather than cout.
Mar 12 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

3
8257
by: Victor Irzak | last post by:
Hello, I have an ABC. it supports: ostream & operator << I also have a derived class that supports this operator. How can I call operator << of the base class for derived object??? Is it at all possible?
5
1870
by: Eric Lilja | last post by:
Ok, this code doesn't compile: #include <iostream> #include <ostream> /* Just for you, Mike :-) */ template<typename T> class Couple { public: Couple(const T& ax, const T& ay) : x(ax), y(ay) {}
4
1417
by: jalkadir | last post by:
This program does compile, but the linker says: main.o(.text+0x1a4):main.cpp: undefined reference to `jme::operator<<(std::ostream&, jme::Name const&)' here is the program's snips. --------- strtools.hpp namespace{ calss strtools{
2
2171
by: Harry | last post by:
Hi all, I am writing a logger program which can take any datatype. namespace recordLog { enum Debug_Level {low, midium, high}; class L { std::ofstream os; Debug_Level cdl; const Debug_Level ddl;
12
6090
by: Filipe Sousa | last post by:
Hi! Could someone explain to me why this operation is not what I was expecting? int main() { int x = 2; std::cout << x << " " << x++ << std::endl; return 0; }
6
1608
by: johnmmcparland | last post by:
Hi all, when I write a subclass, can I inherit its superclass' << operator? As an example say we have two classes, Person and Employee. class Person has the << operator; /**
1
2697
by: buburuz | last post by:
Hi, I have a question about overloading operator<< . Actually I am trying to understand how it works when chaining multiple calls to this operator. I have a very simple class (MyOut) with an overloaded operator<<, which takes a string as input parameter and returns a reference to an ostream object (std::cout in this case). In the main file I instantiate an object of MyOut and then write a message to console in two different ways: 1....
4
1776
by: aaragon | last post by:
Hi everyone, I was unable to find out why my code is not compiling. I have a template class and I'm trying to write the operator<< for standard output. Does anyone know why this is not right? The code is as follows... // main class: template < class Individual,
2
2830
by: soy.hohe | last post by:
Hi all I have a class StreamLogger which implements operator << in this way: template <class TStreamLogger& operator<<(const T& t) { <print the stuff using fstream, etc.> return *this; }
3
4255
by: Martin T. | last post by:
Hello. I tried to overload the operator<< for implicit printing of wchar_t string on a char stream. Normally using it on a ostream will succeed as std::operator<<<std::char_traits<char> will be called. However, I am using the boost::format library that internally makes use of a string stream to store the formatted string. There:
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8335
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8528
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.