mercredi 2 septembre 2015

c++ template auto parameter

I am trying to write a logging routine that (almost) automatically traces the entry and exit to a method. Something like:

int rc=0;
LOG_ENTRY("MyFunction()", rc);

LOG_ENTRY is a macro that defines a local object. When the object is created it will call the logger with "Entry MyFunction()" and when the object is destroyed at the end of the traced method, the destructor will issue "Exit MyFunction() returned 0" where 0 is the value of rc on exit.

Now I have most of this working using c++ except that the constructor for the class for the logging object has to be defined for every type of return value:

class IM_EX_CTIBASE LogEntry
{
    Log *logger;
    const char* func;
    void *rc;
public:
    LogEntry(Log *logger, const char* func, int *rc)
    {
        this->logger=logger;
        this->func=func;
        this->rc=rc;
        logger->log("Entry " << func);
    }
    ~LogEntry()
    {
        logger->log("Exit " << func << *rc);
    }
}

(please forgive any typos, this is a simplified version of the actual code.)

Now I was hoping to rewrite this as a template, where the type rc could be externally defined. I was thinking that auto would be an excellent possibility for defining rc on the constructor, but auto does not work there.

Since the compiler already knows what the type is, why do I need to define it here. the log() (which accepts a stream) should already know how to use rc.

I've looked at many alternatives, but nothing seems to be what I want. Someone suggested "do it like make_pair does", but after digging into that it appears to create a function template which I don't think you can use in a constructor.

Anyone have any ideas?

Aucun commentaire:

Enregistrer un commentaire