如何转换为变量类名
How could I cast to a variable class name?
我有一些类和一个指针,其中一个类是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);
}
这不是很优雅,虽然-但你当然可以这样做,如果你必须(但最有可能有一个更好的解决方案,你的问题)。
相关文章:
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 是否可以将已经初始化的变量转换为 void*?
- C++字符串类如何将一个变量转换为另一个变量?
- std::chrono::time_point 从变量转换时编译器错误
- std::变量转换构造函数行为
- 尝试将字符串变量转换为布尔值会导致 "true" 和 "false" 都等于 0
- C++将字符变量转换为字符串变量将返回 ASCII 值
- 将大端序的 32 位变量转换为小端序
- 在代码优化过程中,C++11编译器是否会在可能的情况下将局部变量转换为右值
- 有符号浮点变量转换为无符号DWORD
- 将初始变量转换为已声明的变量
- 将C++字符串变量转换为long
- 如何将DWORD或char*类型的变量转换为LPCWSTR
- 如何在 c++ 中将包含时间的字符串变量转换为time_t类型
- C++变量转换为模板参数
- 将 [char] 变量转换为 [int],然后再转换回 [char]
- 如何将 int 变量转换为 ASCII 单词
- 将c++类的私有变量转换为公有变量
- 将变量转换为const
- 如何将方法返回的接口变量转换为对象