[英]Conversion from 'void *' to 'vector<int *>'
I am casting a vector pointer as a void pointer to a function.我将向量指针转换为指向 function 的 void 指针。 In that function, how to I cast it to a vector pointer?
在那个 function 中,我如何将它转换为向量指针?
in main
vector<int *> foo;
function(&foo);
in function
function(void *bar){
auto temp = bar; // what replaces auto or what should bar be cast to?
temp.pushback(something);
}
I hope I have not mangled the terminology, any opinion helps!我希望我没有破坏术语,任何意见都有帮助!
You are not casting it, but thats just an implicit conversion.您没有强制转换它,但这只是一种隐式转换。 The method is called
push_back
and you need ->
to dereference.该方法称为
push_back
,您需要->
取消引用。
If you are absolutely certain that the void*
points to a vector<int*>
you can safely cast it back:如果您绝对确定
void*
指向vector<int*>
您可以安全地将其转换回:
#include <vector>
void function(void *bar){
auto temp = static_cast<std::vector<int*>*>(bar);
temp->push_back(new int);
}
int main() {
std::vector<int *> foo;
function(&foo);
}
However, the question arises: Why all the pointers?然而,问题出现了:为什么所有的指针? If by any means you can change
function
and the vector is supposed to store integers your code should look like this:如果您可以通过任何方式更改
function
并且该向量应该存储整数,则您的代码应如下所示:
#include <vector>
void function(std::vector<int>& v){
v.push_back(42);
}
int main() {
std::vector<int> foo;
function(foo);
}
You can apply static_cast
.您可以应用
static_cast
。
Here is a demonstrative program.这是一个演示程序。
#include <iostream>
#include <vector>
void function( void *bar )
{
auto pv = static_cast<std::vector<int *> *>( bar );
for ( const auto &p : *pv ) std::cout << *p << ' ';
std::cout << '\n';
}
int main()
{
int a[] = { 1, 2, 3 };
std::vector<int *> v;
for ( auto &x : a ) v.push_back( &x );
function( &v );
return 0;
}
The program output is程序 output 是
1 2 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.