I'm writing a class to do timing analysis; it "remembers" the time of various points in the code and dumps its results on request.
It works.
But I'd like to have it dump the results by calling an existing logger function. I'm close but can't get it to compile. Here's a short version:
class TheLogger
{
public:
TheLogger() {}
void log(const char* format, ...)
{
va_list argptr;
va_start(argptr, format);
vfprintf(stderr, format, argptr);
va_end(argptr);
}
};
// And there's a different unrelated logger with same signature
class AnotherLogger
{
public:
TheLogger() {}
void logMessage(const char* format, ...)
{
va_list argptr;
va_start(argptr, format);
vsprintf(buf, format, argptr);
va_end(argptr);
doSomething(buf);
}
};
class TqTimingPoint
{
public:
TqTimingPoint(const std::string &name, void (*logger)(const char* format, ...) ) :
mName(name),
mpLoggerFcn(logger)
{ }
void dump()
{
(this->mpLoggerFcn)( mName.c_str() );
}
private:
std::string mName; // Name of this collector
void (*mpLoggerFcn)(const char* format, ...);
};
int
main(int, char **)
{
TheLogger *pLogger = new TheLogger;
pLogger->log("yo baby\n");
TqTimingPoint tp1("testCom", &TheLogger::log);
AnotherLogger *pLogger2 = new AnotherLogger;
TqTimingPoint tp2("testCom", &AnotherLogger::logMessage);
}
I can't figure out how to pass the logger function to the TqTimingPoint
constructor.
TqTimingPoint tp("testCom", &pLogger->log);
complains that ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say ‘&TheLogger::log’
while trying that:
TqTimingPoint tp("testCom", &TheLogger::log)
complains of
no matching function for call to ‘TqTimingPoint::TqTimingPoint(const char [8], void (TheLogger::*)(const char*, ...))’
I'd like the TimingPoint class to accept any logger function as long as it has the same varargs signature. It shouldn't have to hard code TheLogger::
anywhere in it.
So, I suppose I need to cast TheLogger::log in main() but I none of the combinations I've tried work...
(If the logger function is defined at the global scope it works fine. Problems exist only with a log
method within a class)
EDIT I
A few constraints I didn't mention before:
a) the logger class is not "mine" and cannot be modified. So stuck with the signature it provides. (and the real logger class is more complicated, and yes, does use a non-static log()
member
b) Compiler is gcc -std=cxx+11
c) TqTimingPoint
cannot be aware of (hardcode in) a specific logger class because there is a different, unrelated logger AnotherLogger
which happens to have the same signature