Stringified template argument
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 Stringifying template arguments
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.
Have you tried typeid()
as suggested in Stringifying template arguments ?
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<> 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>
精彩评论