• Advertisement

Archived

This topic is now archived and is closed to further replies.

mapping template parameter to char*

This topic is 5498 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi i was wondering if there was a way to map the parameters of a template to their string equivalent: example: template < typename B > class A { const char * getTypeName() { static char * name = NULL; if (name != NULL) { //can the following line be done in any way? //Of couse B is not a char * but can it be converted? sprintf(name, "%s", B); } return name; } } thanks

Share this post


Link to post
Share on other sites
Advertisement
Depends on compiler whether you get this information or not:

  
template <typename B>
class A {
const char* getTypeName() {
return typeid(B).name();
}
}
(never tested)

Share this post


Link to post
Share on other sites
hey thanks, but is it possible to do it a compile time as opposed to run time? Thanks again

Share this post


Link to post
Share on other sites
Yes, but I think you'll then have to manually type the name of each type. Like:

    
template<class T>
inline const char* getTypeName() { return "No type name specified"; }
inline const char* getTypeName<int>() { return "int"; }
inline const char* getTypeName<MyClass>() { return "MyClass"; }

template <typename B>
class A {
const char* getTypeName() {
return ::getTypeName<B>();
}
}

Maybe there's better solution. Probably not. Macro will help a bit.

[edited by - civguy on February 2, 2003 5:08:30 PM]

Share this post


Link to post
Share on other sites
If the type of a symbol is known at compile-time, as is the case with template parameters and with any non-polymorphic type, a typeid expression will be ''optimized away'', and directly substituted with its result.


[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]

Share this post


Link to post
Share on other sites

  • Advertisement