Concatenating two C++ statements - c++

I have simple logging class as below.
#include <iostream>
#include <string>
using namespace std;
class log
{
public:
log(){};
~log(){};
log & operator << ( int x ){ cout << x; return * this;}
log & operator << ( string x ){ cout << x; return * this;}
log & operator << ( log & (log::*pf)() ){ (this->*pf)(); return * this;}
log & end( ) { cout << "\r\n"; return * this;}
};
log l;
#define end &log::end;
#define error( z ) l << "ERROR " z << end;
#define warn( z ) l << "WARN " z << end;
int main()
{
int y = 20;
error ( << y );
}
Is there any way that I can write my code in main like this?
error << y;
Basic idea here, is to avoid user to use macro end
i.e. I do not want user to code like below
error << y << end;

Look like you are reinventing the square wheel to me ! Indeed, there are a lot of logger library out there (boost.log is a good one). Another solution is to have the user write the standard syntax including the call to std::endl:
error << x << std::endl;
warn << y << std::endl;
You can do that by passing a string "warn" or "error" to the construtor of class log.
You have to intercept the std::endl parameter as described in Overload handling of std::endl?.

What about:
#define LOG(Msg) do { l << Msg << ::std::endl; } while(0)
Log("Hello" << "World");
Note: I use a macro like this in debug builds and make it ((void)0) in release builds.
For common logging you should not use a macro and may consider stream manipulators.

One option would be to remove your global variable and use your destructor to write the newline by having the macros create a scope so the object is destroyed:
#define error( z ) {log l; l << "ERROR " z; }
#define warn( z ) {log l; l << "WARN " z; }
That would yield code close to what it appears you want without your end macro:
int y = 20, z = 40;
error ( << y << " " << z);
If you like that approach you might want to look into improving the macro so log levels are enforced in the macro itself so objects are not created with every log message that have nothing to do, if performance at that level matters to you.
Don't see a plug for POCO logging anywhere in here, that's what I use. Not saying that would work for you, it's just what I like for my particular needs.

You may create class:
class PrefixLog
{
public:
explicit PrefixLog(const char* prefix) : prefix(prefix) {}
template <typename T>
log& operator << (const T& t) const { return l << prefix << t << &log::end; }
private:
const char* prefix;
};
PrefixLog error("ERROR ");
PrefixLog warning("WARN ");
And then
warning << y;
error << y;

Related

How to implement a logging macro with automatic newline in C++

In the C++ library glog (Google logging module) there is a nice interface where you can write
LOG(INFO) << "abc " << my_var;
and at runtime it prints something like abc 5\n at runtime (if my_var was 5) where it automatically terminated with a newline.
This is much superior to having to always terminate with std::endl as in
std::cout << "abc " << my_var << std::endl;
What is the simpliest way (code + macros) do I need to replicate this effect in my code?
I think the idea is to return a temp wrapper object:
#include <iostream>
struct Log
{
~Log(void) { ::std::cout << ::std::endl; }
};
template<typename T> Log &&
operator <<(Log && wrap, T const & whatever)
{
::std::cout << whatever;
return ::std::move(wrap);
}
int main()
{
Log() << "whatever";
Log() << "more";
return 0;
}
online compiler
Note that the macro can be used here to execute conditional branching in the beginning of logging. That is skip logging if severity level is low.
#define LOG(level) \
if(g_log_lelevel <= level) Log()

How do I stream into a string without creating a named stringstream?

I often end up writing code like this:
SomeStreamableType x;
std::stringstream ss;
ss << "Value is: " << x;
log(ss.str());
The extra line needed to generate the stringstream feels superfulous. I can do this, but it's equally cumbersom:
SomeStreamableType x;
const std::string str = "Value is: " + boost::lexical_cast<std::string>(x);
log(str);
I want to be able to do this:
SomeStreamableType x;
log(std::stringstream() << "Value is: " << x);
Have others encountered this issue and come up with a workaround? I don't want to create any helper functions or classes.
Your code will work without modifications, as long as log accepts an ostream& reference:
void log(ostream& o) {
stringstream* s = dynamic_cast<stringstream*>(&o);
if (s) {
cout << s->str() << endl;
}
}
int main() {
int x = 5, y = 6;
log(stringstream() << "x=" << x << ", y=" << y);
return 0;
}
Demo.
To solve this problem I have often simply done something like this:
#define LOG(m) do{std::ostringstream oss;oss<<m;std::cout<<oss.str()<<'\n';}while(0)
// ...
LOG("some text: " << value1 << ' ' << value2); // no need for '\n'
Now I tend to use a more sophisticated class based solution that has an even nicer interface and doesn't use a horrible macro.

Printing a pointer-to-member-field

I was debugging some code involving pointers to member fields, and i decided to print them out to see their values. I had a function returning a pointer to member:
#include <stdio.h>
struct test {int x, y, z;};
typedef int test::*ptr_to_member;
ptr_to_member select(int what)
{
switch (what) {
case 0: return &test::x;
case 1: return &test::y;
case 2: return &test::z;
default: return NULL;
}
}
I tried using cout:
#include <iostream>
int main()
{
std::cout << select(0) << " and " << select(3) << '\n';
}
I got 1 and 0. I thought the numbers indicated the position of the field inside the struct (that is, 1 is y and 0 is x), but no, the printed value is actually 1 for non-null pointer and 0 for null pointer. I guess this is a standard-compliant behavior (even though it's not helpful) - am i right? In addition, is it possible for a compliant c++ implementation to print always 0 for pointers-to-members? Or even an empty string?
And, finally, how can i print a pointer-to-member in a meaningful manner? I came up with two ugly ways:
printf("%d and %d\n", select(0), select(3)); // not 64-bit-compatible, i guess?
ptr_to_member temp1 = select(0); // have to declare temporary variables
ptr_to_member temp2 = select(3);
std::cout << *(int*)&temp1 << " and " << *(int*)&temp2 << '\n'; // UGLY!
Any better ways?
Pointers to members are not as simple as you may think. Their size changes from compiler to compiler and from class to class depending on whether the class has virtual methods or not and whether it has multiple inheritance or not. Assuming they are int sized is not the right way to go. What you can do is print them in hexadecimal:
void dumpByte(char i_byte)
{
std::cout << std::hex << static_cast<int>((i_byte & 0xf0) >> 4);
std::cout << std::hex << static_cast<int>(i_byte & 0x0f));
} // ()
template <typename T>
void dumpStuff(T* i_pStuff)
{
const char* pStuff = reinterpret_cast<const char*>(i_pStuff);
size_t size = sizeof(T);
while (size)
{
dumpByte(*pStuff);
++pStuff;
--size;
} // while
} // ()
However, I'm not sure how useful that information will be to you since you don't know what is the structure of the pointers and what each byte (or several bytes) mean.
Member pointers aren't ordinary pointers. The overloads you expect for << aren't in fact there.
If you don't mind some type punning, you can hack something up to print the actual values:
int main()
{
ptr_to_member a = select(0), b = select(1);
std::cout << *reinterpret_cast<uint32_t*>(&a) << " and "
<< *reinterpret_cast<uint32_t*>(&b) << " and "
<< sizeof(ptr_to_member) << '\n';
}
You can display the raw values of these pointer-to-members as follows:
#include <iostream>
struct test {int x, y, z;};
typedef int test::*ptr_to_member;
ptr_to_member select(int what)
{
switch (what) {
case 0: return &test::x;
case 1: return &test::y;
case 2: return &test::z;
default: return NULL;
}
}
int main()
{
ptr_to_member x = select(0) ;
ptr_to_member y = select(1) ;
ptr_to_member z = select(2) ;
std::cout << *(void**)&x << ", " << *(void**)&y << ", " << *(void**)&z << std::endl ;
}
You get warnings about breaking strict anti-aliasing rules (see this link), but the result is what you might expect:
0, 0x4, 0x8
Nevertheless, the compiler is free to implement pointer-to-member functionality however it likes, so you can't rely on these values being meaningful.
I think you should use printf to solve this problen
#include <stdio.h>
struct test{int x,y,z;}
int main(int argc, char* argv[])
{
printf("&test::x=%p\n", &test::x);
printf("&test::y=%p\n", &test::y);
printf("&test::z=%p\n", &test::z);
return 0;
}

How to make thread safe Log class that supports `<<` operations?

So I have such log class:
#include <iostream>
#include <sstream>
#include <boost/circular_buffer.hpp>
#include <boost/foreach.hpp>
class FlushInternal;
class Log
{
public:
static FlushInternal* endl;
Log(int log_length)
{
i = 0;
messages_buffer = new boost::circular_buffer<std::string>(log_length);
}
template <class T>
Log &operator<<(const T &v)
{
current_message << v;
return *this;
}
Log &operator<<(std::ostream&(*f)(std::ostream&))
{
current_message << *f;
return *this;
}
Log &operator<<(FlushInternal*)
{
++i;
messages_buffer->push_back(current_message.str());
clean_stringstream(current_message);
is_filled();
return *this;
}
boost::circular_buffer<std::string> *messages_buffer;
private:
int i;
std::stringstream current_message;
void is_filled()
{
if (i >= messages_buffer->capacity())
{
i = 0;
BOOST_FOREACH(std::string s, *messages_buffer)
{
std::cout << ++i << ": " << s << " ;" << std::endl;
}
i = 0;
}
}
void clean_stringstream(std::stringstream &message)
{
message.flush();
message.clear();
message.seekp(0);
message.str("");
}
};
FlushInternal* Log::endl = 0;
And I can Use it like this:
#include <log.h>
int main()
{
Log l(2);
l << "message one: " << 1 << Log::endl;
l << "message two:" << " " << 2 << Log::endl;
l << "message " << "three: " << 3 << Log::endl;
l << "message" << " " << "four: " << 4 << Log::endl;
std::cin.get();
}
This would output:
1: message one: 1 ;
2: message two: 2 ;
1: message three: 3 ;
2: message four: 4 ;
As you can see I can have as many << as I want inside each log message. I want to be capable to use one instance of Log class from many threads at the same time. So I would have something like (pseudocode that compiles, runs but traces nothing.):
#include <boost/thread.hpp>
#include <log.h>
Log *l;
void fun_one()
{
*l << "message one: " << 1 << Log::endl;
*l << "message two:" << " " << 2 << Log::endl;
}
void fun_two()
{
*l << "message " << "three: " << 3 << Log::endl;
*l << "message" << " " << "four: " << 4 << Log::endl;
}
int main()
{
l = new Log(2);
boost::thread(fun_one);
boost::thread(fun_two);
std::cin.get();
}
So as you can see I want messages to be inserted into log in multythreaded function. Lo I wonder - how to make my log cclass support this?
The approach linked by trojanfoe is pretty much the canonical one. Basically create some temporary thing for the leftmost << operator, accumulate everything, and output the message in the destructor for the temporary thing.
The only question is the exact mechanics of this accumulator. The example used ostringstream, but I've seen the ofstream for the log file used directly as well (requires locking to ensure the output ends up on one line).
Creating ostringstreams is relatively expensive on some platforms, because they may need to lock and copy some internal locale related things. You could re-implement also the << operator for interesting types, but I'd test the ostringstream approach first.
A useful optimization is determine at the point of the construction of the temporary whether the trace will be emitted (e.g., whether tracing is enabled at that particular level), and not create the guts of the temporary at all in that case - all the insertion operations will be no-ops.
Here's one approach:
http://drdobbs.com/cpp/201804215
It basically creates a new ostringstream object each time you perform logging, which makes it thread safe. I can't say I'm that keen on that, as it seems a little clumsy to me.
You might have a look at the Qt logging classes as they support the << operator, however I'm not sure about thread safety.

Printing detailed debugging output easily?

I'm basically looking for a way to automate typing stuff like the following:
cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl;
Something like:
PRINTDBG(a[x][y]);
Ideally this would also work for
PRINTDBG(func(arg1, arg2));
and even
PRINTDBG(if(condition) func(foo););
(which would print e.g. "if(false) func(5)").
Nonportable hacks welcome too :)
(no, using a debugger isn't the same, it's much less flexible and I find it confusing)
This is, in the way you want it, not possible. If you have if(condition) func(foo); given to a macro, it can stringize that stuff, and it will print if(condition) func(foo);, but not with the actual values of the variables substituted. Remember the preprocessor doesn't know about the structure about that code.
For debugging, i would use some type-safe printf variant like boost.format or some home brew printf with boost.fusion, which make the job of printing stuff like that much more easy:
dprintf("a[%][%] = %", (x, y, a[x][y]));
This is an area where the printf style output can be more concise:
cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl;
printf("a[%d][%d] =\t%d\n", x, y, a[x][y]);
Of course, this has the limitation of only working for types that printf understands, and it still doesn't address your question.
I get the feeling that there might be something of value in the expression decomposition techniques in Boost, but I am not enough of a template ninja to identify what.
Update: The following almost addresses your question:
#define PRINTDBG(x) cout << #x << " =\t" << x << endl;
However, when used as PRINTDBG(a[x][y]) it literally prints:
a[x][y] = 5
which doesn't give the actual values of x and y.
I typically use a simple, but customizable logger function instead of macros
Log(const char *format, ...)
{
char buffer[MAX_BUFFER_SIZE];
va_list args;
//get arguements into a list
va_start(args, format);
//printf formated arguement into a string
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
printf("%s", buffer);
}
so now you can do
Log("a[%d][%d] =\t%d\n", x, y, a[x][y])
Log("if(%s) func(%d) ;", (condition) ? "true" : "False", func(foo))
add in some loggingtype (i.e. LOG_SCREEN, LOG_FILE) to the function Log() and now you can control where is gets logged to
add in some logginglevel (i.e. WARN, CRIT) to control how it gets displayed, color etc.
Of course there are many, many library's out there that do all this type of stuff already
hope this helps
In a slight expansion in a different direction to Greg's posting, I've seen some nice C programs that look something like this
#DEFINE DEBUG_MODE 1
//...
if( DEBUG_MODE)
printf("methodX() says: y=%i, var1=%i", y, var1);
However you still have a ton of printf's in your program, but at least you can turn them all on and off when you want to.
you can define operatorĀ« for custom classes so you only have to define formatting once:
struct point3 {
int x,y,z;
point3(int a, int b, int c){x=a;y=b;z=c;}
};
std::ostream& operator << (std::ostream& os, const point3& f) {
return os << "(" << f.x << "," << f.y << "," << f.z << ")";
}
point3 p(1,2,3);
std::cout << p; // prints "(1,2,3)"
this pairs well with redirecting cout or clog to a file (don't recall how std::clog works)
#include <iostream>
#include <fstream>
int main() {
std::ofstream file("log.txt");
std::streambuf *filebuf = file.rdbuf();
std::cout.rdbuf(filebuf);
std::cout << "This is written to the file";
filestr.close();
return 0;
}