如何传递std :: vector< void *> *作为函数的std :: vector< mystruct *> * [英] How to pass std::vector<void*> * as std::vector<mystruct*>* to a function

查看:241
本文介绍了如何传递std :: vector< void *> *作为函数的std :: vector< mystruct *> *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





如何传递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 valid MyStruct 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&lt; void *&gt; *作为函数的std :: vector&lt; mystruct *&gt; *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆