c++ - Make a wrapper for cout? -
so here's interesting question, how make kinda wrapper cout? want able add dll can throw programs. basic syntax of should be
mything::mesage << "i'm text" << im_an_int << someclass << mything::endl;
or
mything::mesageandlog << "i'm going print console, , file!" << mything::endl;
i can handle of internal logic should put this. kinda stumped.
possibly make static stream member in class called message, have event fire when written runs through method?
idk, looked around , found sorta similar, throwing dll i'm @ loss. (how write function wrapper cout allows expressive syntax?) because requires me use extern , variable, how make static can straight call without creating variable?
bit of clarification, this: mydll.h
#include <iostream> namespace mynamespace { extern struct logmessage{}; template <typename t> logmessage& operator<< (logmessage &s, const t &x) { setstdhandle(std_output_handle, getstdhandle(std_output_handle)); setconsoletextattribute(getstdhandle(std_output_handle),foreground_blue); std::cout << "[if] "; setconsoletextattribute(getstdhandle(std_output_handle),foreground_white); //logtimestamp(); --ill impliment this. std::cout << x << endl; //writestreamtologfile(s); --and ill handle this. return s; } }
driverprogram.h
#include <mydll.h> #include <iostream> int _tmain(int argc, _tchar* argv[]) { mynamespace::logmessage << "something: << std::endl; }
expected output:
"[if] [00:00:00]
you can create struct, has << operator
struct outputthing { template< class t > outputthing &operator<<( t val ) { std::cout<<val; return *this; } };
now whenever want log, have instance object.
outputthing()<<"x ="<<x;
if want avoid repeated construction , destruction of object, can make singleton.
struct outputthingsingleton { static outputthingsingleton& getthing() { static outputthingsingleton outputthing; return outputthing; } template< class t > outputthingsingleton &operator<<( t val ) { std::cout<<val; return *this; } private: outputthingsingleton() {}; };
so call looks
outputthingsingleton::getthing()<<"x ="<<x;
which shorten using macro.
this work across multiple dlls, depending on how used can have multiple instances of singleton existing. work fine long don't want maintain state in singleton. if need ensure single instance, can compile in own dll. other binary uses dll share single instance 'owned' dll.
Comments
Post a Comment