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? -
#include <iostream>
-
-
class Logger {
-
public:
-
template <typename T>
-
Logger& operator << (const T &t)
-
{
-
// do sth with t
-
std::cout << t;
-
return *this;
-
}
-
};
-
-
int main()
-
{
-
Logger log;
-
-
log << "Hello " << 10 << 20; // ok
-
log << std::endl; // fault here
-
-
}
-
5 5717
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: - 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.
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?
You have Logger object right? - Logger obj( the parameters);
-
-
obj.SetFormat(parameters for formatting the log);
-
-
//etc...
-
-
cout << obj << endl;
The code above is a call to - ostream& operator<<(ostream&, Logger&);
followed by a call to - ostream& operator<<(ostream&, ostream& (*)(ostream&));
The second call is for the endl. The second function is provided by the C++ Library.
You could also: - cout << Logger(the parameters) << endl;
That would create a Logger object which would be used an then deleted when the satement was complete.
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.
You might try: - class Logger {
-
private:
-
ofstream theLog;
-
public:
-
Logger();
-
template <typename T>
-
Logger& operator << (const T &t)
-
{
-
// do sth with t
-
this->theLog << t;
-
return *this;
-
}
-
-
};
-
Logger::Logger(): theLog("TheLogFile.txt")
-
{
-
-
}
-
-
int main()
-
{
-
Logger log;
-
-
log << "Hello " << 10 << 20; // ok
-
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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?
|
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) {}
|
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{
|
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;
|
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;
}
| |
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;
/**
|
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....
|
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,
|
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;
}
|
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:
|
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...
| |
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,...
|
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...
|
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,...
|
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...
|
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...
|
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...
| |
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();...
|
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...
| |