开发者

Convert templated parameter type to string

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 li开发者_JAVA百科ke 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜