Obtaining the type-name of a template type, withou

2019-07-20 16:33发布

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)

标签: c++ boost c++11
2条回答
在下西门庆
2楼-- · 2019-07-20 17:16

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.

查看更多
我只想做你的唯一
3楼-- · 2019-07-20 17:17

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.

查看更多
登录 后发表回答