如何转换为变量类名

How could I cast to a variable class name?

本文关键字:变量 转换 何转换      更新时间:2023-10-16

我有一些类和一个指针,其中一个类是void*,指向这些类之一。

我还在一个字符串变量中有那个类的名称,我想将那个void指针强制转换到那个类。

我想做这样的事情:

    string className;
    className = "int";
    (className *) voidPointer;

有办法吗??

提前感谢!

这是不可能的。

然而,我认为boost::any可以帮助你:

boost::any obj;
if (className == "int")
   obj = (int)voidPointer;
else if (className == "short")
   obj = (short)voidPointer;
//from now you can call obj.type() to know the type of value obj holds
//for example
if(obj.type() == typeid(int))
{
    int value = boost::any_cast<int>(obj);
    std::cout <<"Stored value is int = " << value << std::endl;
}

即使用boost::any_cast获取存储在boost::any类型对象中的值

c++没有反射,所以你不容易做到这一点。

你能做的就是在这几行

string classname;
void * ptr;
if ( classname == "Foo" )
{
    Foo* f = static_cast<Foo*> ( ptr );
}
else if ( classname == "Bar" )
{
    Bar* f = static_cast<Bar*> ( ptr );
}

不行,你不能这么做。不过,您可以使用模板类来实现这一点。注意,我提供了一个解决方案,但我不认为你应该存储一个void*指针。

template<class T>
T* cast(void* ptr) { return static_cast<T*>(ptr); };

然后,你可以这样做:

int* intPtr = cast<int>(ptr);

我重复一遍,你可能根本不需要使用void*

当然可以:

if (className == "int") {
  int *intPtr = static_cast<int*>(voidPointer);
}

这不是很优雅,虽然-但你当然可以这样做,如果你必须(但最有可能有一个更好的解决方案,你的问题)。