1

Possible Duplicate:
C++ return array from function

I am trying to declare a function that returns an array of void pointers. I have the following code:

void *[] get_functions();

However I get the compilation error: expected unqualified-id before '[' token

Is what I'm trying to do valid, and if so what is my syntax error?

EDIT In reply to some of the comments, I am trying to return an array (which now will probably be a vector) of functions, which I can then randomly select one and call it. What would you suggest instead of void *?

EDIT 2 The type of functions returned will have a fixed signature (not decided yet), Let's for arguments sake say the signature will be int f(int i, int j) what would the return of my get_functions function look like, or will vector<void*> still be appropriate?

4

4 に答える 4

7

C++ doesn't allow a function to return an array. You should probably return a vector instead:

std::vector<void *> get_functions();
于 2012-10-11T11:50:05.730 に答える
2

There are two issues with your approach. The first of which is that you cannot return arrays from functions. In C you would return a pointer to the elements in the array, but that implies that you need to manage the memory. In C++ you can use a container, like std::vector instead of the array, and that can be returned by value.

The second issue is that you are returning function pointers, and the conversion from function pointer to void* is not guaranteed by the standard. The alternatives here start with returning a function pointer of the appropriate type (i.e. std::vector<int (*)(int,int)>) or using higher level constructs like std::function (C++11, or boost::function in C++03): std::vector<std::function<int(int,int)>>. The first approach is better suited for the description you provided as the types of the functions seem to be fixed and there will be little overhead in using the function pointers. The second approach is more generic as it can encapsulate anything that is callable with two int and return an int, including function pointers and function objects. That in turn allows you to adapt the signatures of other functions by means of std::bind or create lambdas with the appropriate signature: [](int x, int y){ return x*y;}

于 2012-10-11T13:17:19.410 に答える
1
void **get_functions();

Later on you can then say:

void **pp = get_functions();
pp[5];     // This is the sixth pointer-to-void

If you don't already know the length of the array, you will need to pass it some other way -- for that reason, Jerry Coffin's answer is probably better.

于 2012-10-11T11:52:54.417 に答える
0

配列の最初の要素へのvoidポインタを返すことができます。呼び出し元の関数内にキャストできます。配列自体はポインタとして渡されたり返されたりします。

于 2012-10-11T12:08:14.877 に答える