我正在尝试使用std :: vector,我不知道它的类型。我已经能够转换向量并将其传递给函数和从函数传递。但我无法弄清楚是否可以在不知道对象类型的情况下访问向量中的对象。我知道对象总是指针。是否可以在不知道对象类型的情况下访问向量及其所拥有的对象的大小?
我在下面添加了一个示例用例。我遇到的问题是在MyTariant :: VarTypeObjectArray的情况下在PushToLua()函数中:
下面的代码允许我做这样的事情......
int main( int argc, char *argv[] )
{
std::vector<SomeClass*> vec;
MyVariant v = &vec;
std::vector<SomeClass*>* test = v;
v.PushToLua();
}
class SomeClass
{
};
class Wrapper
{
};
template<typename ValueType>
class ContainerWrapper : public Wrapper
{
public:
ContainerWrapper( ValueType value )
: m_Container( value )
{
}
ValueType GetValue()
{
return m_Container;
}
ValueType m_Container;
};
class MyVariant
{
public:
enum VarType
{
VarTypeVoid,
VarTypeInt,
VarTypeUnsignedInt,
VarTypeFloat,
VarTypeObjectArray
};
union
{
int m_Int;
unsigned int m_UnsignedInt;
float m_Float;
Wrapper* m_ObjectArray;
};
VarType m_Type;
template<typename ValueType>
MyVariant( std::vector<ValueType*>* value )
{
//note--not concerned with the "new" and no delete right now. just testing
ContainerWrapper<std::vector<ValueType*>*>* pTemp = new ContainerWrapper<std::vector<ValueType*>*>( value );
m_Type = VarTypeObjectArray;
m_ObjectArray = pTemp;
}
template<typename T>
operator std::vector<T*>*()
{
if ( m_Type == VarTypeObjectArray )
{
ContainerWrapper<std::vector<T*>*>* pWrapper = static_cast<ContainerWrapper<std::vector<T*>*>*>(m_ObjectArray);
return pWrapper->GetValue();
}
return NULL;
}
bool MyVariant::PushToLua( lua_State* L ) const
{
switch ( m_Type )
{
case MyVariant::VarTypeInt:
case MyVariant::VarTypeUnsignedInt:
//lua_pushinteger( L, m_Int );
return true;
case MyVariant::VarTypeFloat:
//lua_pushnumber( L, m_Float );
return true;
case MyVariant::VarTypeObjectArray:
lua_newtable( L );
//Somehow loop through array and push each address into table
//I won't know the type here, but i do know its an object
// ? = cause i can't figure out how
// I guess the question is, how can i do this?
ContainerWrapper<std::vector<?*>*>* pWrapper = static_cast<ContainerWrapper<std::vector<?*>*>*>(m_ObjectArray);
std::vector< ?* >* myArrayOfObjects = pWrapper->GetValue();
int i = 0;
for ( auto& object : myArrayOfObjects )
{
//lua_pushlightuserdata( L, object );
//lua_rawseti( L, -2, i++ );
}
return true;
default:
return false;
};
}
};