[英]How do I declare a C++ prototype with a void * pointer so that it can take any pointer type?
I want to create a function prototype in C++ so that there is a void *
argument that can take pointers of any type. 我想在C ++中创建一个函数原型,以便有一个
void *
参数可以接受任何类型的指针。 I know that this is possible in C. Is it possible in C++? 我知道这在C语言中是可能的。在C ++中是否可能?
[EDIT] Here is a simplified version of the code that I am trying to get to work: [编辑]这是我尝试使用的代码的简化版本:
#include <stdio.h>
void func(void (f)(const void *))
{
int i = 3;
(*f)(&i);
}
void func_i(const int *i)
{
printf("i=%p\n",i);
}
void func_f(const float *f)
{
printf("f=%p\n",f);
}
void bar()
{
func(func_i);
}
And here is the compiler output: 这是编译器的输出:
$ g++ -c -Wall x.cpp
x.cpp: In function ‘void bar()’:
x.cpp:21: error: invalid conversion from ‘void (*)(const int*)’ to ‘void (*)(const void*)’
x.cpp:21: error: initializing argument 1 of ‘void func(void (*)(const void*))’
$ %
You may use void*, just as with C, but you'll need to cast your argument when calling it. 您可以像使用C一样使用void *,但是在调用它时需要转换参数。 I suggest you use a template function
我建议您使用模板功能
template<typename T>
void doSomething(T* t) {...}
How about: 怎么样:
void func(void *);
exactly like in C? 完全像在C中一样? : P
:P
Yes. 是。
int i = 345;
void * ptr = &i;
int k = *static_cast< int* >(ptr);
UPDATE :: What you have shown in the code certainly cannot be done in C++. Casting between void and any other must always beexplicitly done. Check these SO link for more details on what the C -standard has to say: 1) http://stackoverflow.com/questions/188839/function-pointer-cast-to-different-signature 2) http://stackoverflow.com/questions/559581/casting-a-function-pointer-to-another-type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.