如何传递std :: vector< void *> *作为函数的std :: vector< mystruct *> * [英] How to pass std::vector<void*> * as std::vector<mystruct*>* to a function
问题描述
如何传递std :: vector< void *> *作为std :: vector< MyStruct *> *到一个函数?
函数声明是void SetDataReferences(std :: vector< MyStruct *> * pVector );
如果我传递std :: vector< void *> * as std :: vector< MyStruct *> *我收到以下错误
错误C2664:'SetDataReferences':无法从'std :: vector<转换参数2 ; _Ty> *'到'std :: vector< _Ty> *'
如何解决这个问题?
我的尝试:
我不知道它的替代方案。
如果你确定矢量你传递的实际上包含指向有效MyStruct
实例的指针, reinterpret_cast [ ^ ]会做的伎俩。例如,尝试:
#include < iostream >
#include < vector >
使用 namespace std;
struct Foo
{
string s;
int i;
};
void reportFooVector(vector< Foo *> * pvf)
{
for ( auto p:* pvf)
cout<< p-> s<< ,<< p-> i<< ENDL;
}
int main()
{
Foo foo { foo, 5 };
Foo goo { goo, 10 跨度>};
vector< void *> vf {& foo,&咕};
reportFooVector(reinterpret_cast< vector< Foo *> *>(& vf));
}
替代方案非常明确:以正确的类型创建和传递参数。
你应该非常严肃地对待这个警告,因为它尖叫编码缺陷。
// TODO:更改输入的创建代码参数跨度>
Hi,
How to pass std::vector<void*> * as std::vector<MyStruct*>* to a function?
The function declaration is void SetDataReferences(std::vector<MyStruct*>* pVector);
if I pass std::vector<void*> * as std::vector<MyStruct*>* I am getting below error
error C2664: 'SetDataReferences' : cannot convert parameter 2 from 'std::vector<_Ty> *' to 'std::vector<_Ty> *'
How to resolve this?
What I have tried:
I dont know what is the alternative for it.
Provided you are sure the vector you are passing actually contains pointer to validMyStruct
instances, a reinterpret_cast[^] would do the trick. Try, for instance:
#include <iostream> #include <vector> using namespace std; struct Foo { string s; int i; }; void reportFooVector( vector <Foo*> * pvf ) { for (auto p : *pvf) cout << p->s << ", " << p->i << endl; } int main() { Foo foo{ "foo", 5}; Foo goo{ "goo", 10}; vector <void *> vf { &foo, & goo}; reportFooVector( reinterpret_cast< vector < Foo * > * >(&vf)); }
The alternative is very clear: creating and passing the parameter in the right type.
You should take this warning very serious because it screams for a coding flaw.
//TODO: Change the creation code of input parameter
这篇关于如何传递std :: vector< void *> *作为函数的std :: vector< mystruct *> *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!