Re: Type name as string
* Severin Ecker:
Hi,
I'm not aware of any solution but hopefully there is a way that I just
don't know.
Can I get the name of a type as string (literal) in a consistent
platform independent way?
Yes, but as of C++98 you have to implement that yourself -- typeid is
platform-specific.
Since I only need this information statically I could use (and prefer) a
compile time possibility (i.e.: I won't need to query the type name of
an object at runtime), basically it's something like:
template <class T>
struct TypeName
{
static const char* name = //somehow get the name of T;
};
so
TypeName<int>::name == "int";
and
struct bla {};
TypeName<bla>::name == "bla";
I know that the type_info::name is implementation dependent so that's
not an option (additionally it doesn't even have to be related to the
name you type in the code as far as I'm aware of as long as it's
unambiguous) but since the compiler has all the knowledge that I need I
was hoping that there's a way to get the info from it.
In essence what I'm trying/needing to do (and before you ask, yes I do
need the thing as string and can't just let the type system figure it
out for me) is the following (and I really would like to save the
tedious work of dozens of specializations for all the types that can
actually be used for Foo):
template <class T> std::string GetCast(T t) { return ""; };
template <class T> std::string GetCast(T* t)
{
std::string cast("(");
cast += std::string(TypeName<T>::name) + ")";
return cast;
}
Ugh, *generating* bad C code.
Oh well.
Since that's already very dirty, consider using compiler-specific means, and in
the worst case accessing the generated debug information. There is an
introspection library for gcc that may help (for that compiler). But why on
Earth do you want to generate bad C-code based on your C++ program's internals?
Just in case the above example is misleading, I should also mention the
preprocessor's stringizing operator.
The stringizing operator may help you if you know the concrete type name in the
calling code, but not if above example is invoked from code templated on T.
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!