简体   繁体   中英

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. I know that this is possible in C. Is it possible in 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. I suggest you use a template function

template<typename T>
void doSomething(T* t) {...}

How about:

void func(void *);

exactly like in C? : 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 be  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM