Obtaining the type-name of a template type, without class definition
I am trying to write a template wrapper that works with the smart_ptr
type and need to throw an exception in some cases. For this case I'd like to include the name of the type the class is wrapping. As I am working with smart pointers only forward declarations will be available for the type.
So the essential question is how can I get a string for of a template parameter without having its definition available? (I don't need a clean name, anything resembling the name will be fine)
My attempt at using typeid
fails since it requires the class definition (at least in GCC).
The code I essentially need to work is below (which gives an error in GCC)
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
class SomeClass;
void func( shared_ptr<SomeClass> obj );
template<class T>
class Wrap
{
shared_ptr<T> ptr;
public:
shared_ptr<T> get()
{
if( !ptr )
throw std::string(typeid(T).name());
return ptr;
}
};
extern Wrap<SomeClass> wrapSomeClass;
int main()
{
func( wrapSomeClass.get() );
}
(This setup led to my ill-stated previous question -- the error message is kind of confusing)
You could write a code generator that creates a template such as type_string
specialized for all needed types and use that template to get a string. I can't think of any other way that doesn't need the full definition.
Okay, I found a few possibilities; but hopefully somebody else can come up with a better answer.
Use a macro to create the extern, since the # token could grab the name it should be easy enough to get this string to the template.
If I truly don't care about the thrown string I can do
typeid(T*)
since that apparently doesn't need the type.
精彩评论