Obtaining the type-name of a template type, without class definition

被刻印的时光 ゝ 提交于 2020-01-24 12:19:27

问题


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)


回答1:


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.




回答2:


Okay, I found a few possibilities; but hopefully somebody else can come up with a better answer.

  1. 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.

  2. If I truly don't care about the thrown string I can do typeid(T*) since that apparently doesn't need the type.



来源:https://stackoverflow.com/questions/6523878/obtaining-the-type-name-of-a-template-type-without-class-definition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!