开发者

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) {...}


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 explicitly 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


How about:

void func(void *);

exactly like in C? : P

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜