获取的模板类型的类型名,没有类定义 [英] Obtaining the type-name of a template type, without class definition
问题描述
我试图写一个模板,包装与运作的 smart_ptr
键入并需要抛出一个异常,在某些情况下。对于这种情况,我想包括类包装类型的名称。由于我与智能指针工作只能向前声明将提供类型。
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)
我在尝试使用的typeid
失败,因为它需要的类定义(至少在GCC)。
My attempt at using typeid
fails since it requires the class definition (at least in GCC).
在code基本上我需要努力的是低于(这给出了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() );
}
的(这种设置使我生病态previous <一个href=\"http://stackoverflow.com/questions/6523292/forwarding-a-shared-ptr-without-class-declaration\">question - 错误信息是怎么样的混乱)的
(This setup led to my ill-stated previous question -- the error message is kind of confusing)
推荐答案
您可以写一个code发生器创建一个模板,如 TYPE_STRING
专门用于所有需要的类型,并使用该模板来获得一个字符串。我想不出,这并不需要完整的定义,任何其他方式。
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.
这篇关于获取的模板类型的类型名,没有类定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!