views:

76

answers:

3

Is it possible to get a stringified version of a template argument name?

Something like this, if only we were running the preprocessor:

template <typename T>
struct Named{
    const char* name(){ return "Named<" #T ">"; }
};

Edit Duplicate. See here http://stackoverflow.com/questions/1488186/stringifying-template-arguments

+1  A: 

No. The closest thing you can have is typeid(T).name(). However, the result of this is unspecified, even an implementation which returned empty strings for all types would be conforming. For debugging purposes it often is sufficient, though.

sbi
+1  A: 

Have you tried typeid() as suggested in http://stackoverflow.com/questions/1488186/stringifying-template-arguments ?

jdv
+1  A: 

Not without pain. My closest solution:

template <typename T>
struct Named{
    const char* name();
};

#define DEFINE_NAMED(T) template<> const char* Named<T>::name(){ return #T ; };

DEFINE_NAMED(SomeNameSpace::SomeClass)

Of course, this is evil... so far you could use gccxml and xsltproc to automatic find unimplemented Named<T>::name(), create some auxilary file, compile it, and finally link it:

gccxml test.cpp -fxml=test.xml
xsltproc -o Named.cpp Named.xslt test.xml
g++ Named.cpp test.cpp -o test.bin

Some proposal Named.xslt file (duno if work):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text" indent="yes" encoding="utf-8" />

<xsl:template match="Method" >
    <xsl:text>template&lt;&gt; const char* </xsl:text>
    <xsl:value-of select="@demangled" />
    <xsl:text> { return "</xsl:text>
    <xsl:value-of select="substring(@demangled,7,string-length(@demangled)-15)" />
    <xsl:text>"; };
</xsl:text>
</xsl:template>

<xsl:template match="/">
    <xsl:text>#include "Named.h"
</xsl:text>
    <xsl:apply-templates select="/GCC_XML/Method[matches(@demangled,'^Named.*::name()$') and @extern = '1' ]" />
</xsl:template>

</xsl:stylesheet>
lionbest