tags:

views:

64

answers:

1

I've got a small bit of DRY going on in code I and others have written that I'd like to reduce but I'm failing to figure out how to get it done. This is legacy COM code but it's interfering with the readability. I'd like to do the following:

bool queryInterface<class T, class V>(T &_input, V &_output, Logger &_logger){
    if( FAILED( _input->QueryInterface( &_output ) ) ){
        _logger.error() << "Failed to Query Interface between " << MAGICHAPPENS<T>() 
                        << " and " << MAGICHAPPENS<V>();

        return false;
    }
    if( _output == NULL ){
        _logger.warn() << "Unable to Query Interface between " << MAGICHAPPENS<T>()
                       << " and " << MAGICHAPPENS<V>();

        return false;
    }
}

Wherein the "MAGICHAPPENS()" function would spit out the name of the variable type. Such that if "V" were a IQueryFilter I'd get back a string of "IQueryFilter." I can't think of any reasonable solution without having to write a bunch of template specializations totally defeating the point in the first place.

Is there a way to write ANDMAGICHAPPENS?

+2  A: 

You can use RTTI to get the variable name:

#include <typeinfo>

template <typename T>
const char* type_name(void)
{
    // this, unfortunately, is implementation defined
    // and is allowed to be an empty string (useless!)
    return typeid(T).name(); 
}

_logger.error() << "Failed to Query Interface between " << type_name<T>() 
                    << " and " << type_name<V>();

Like the comments say, name() isn't guaranteed to be any particular formatting of the name, or any name at all. But it does require RTTI, which some people dislike.

GMan
Thank you sir. I will try this!
wheaties