簡體   English   中英

如何聲明帶有void *指針的C ++原型,以便它可以采用任何指針類型?

[英]How do I declare a C++ prototype with a void * pointer so that it can take any pointer type?

我想在C ++中創建一個函數原型,以便有一個void *參數可以接受任何類型的指針。 我知道這在C語言中是可能的。在C ++中是否可能?

[編輯]這是我嘗試使用的代碼的簡化版本:

#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);
}

這是編譯器的輸出:

$ 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*))’
$ %

您可以像使用C一樣使用void *,但是在調用它時需要轉換參數。 我建議您使用模板功能

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

怎么樣:

void func(void *);

完全像在C中一樣? :P

是。


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM