开发者

Change return type dynamically?

开发者 https://www.devze.com 2023-02-19 12:35 出处:网络
Let\'s say I 开发者_如何学Chave this method: matrix* multiply(smatrix *sm, matrix *m){ Even if it return matrix * I want to dynamically change its return type. Can I set the return type as void * a

Let's say I 开发者_如何学Chave this method:

matrix* multiply(smatrix *sm, matrix *m){

Even if it return matrix * I want to dynamically change its return type. Can I set the return type as void * and cast it later?


You can declare void* multiply(smatrix *sm, matrix *m) and then typecast the return type later


Yes you can return a void* pointer and cast it into anything you would like. Just make sure you are returning what you expect otherwise you could access the wrong memory.

It may be bad to design the code this way as it can get ambiguous.


You could do the cast in the call to the function.

struct wibble
  *w;

w = (struct wibble *)( multiply(sm, m) );

BTW, you might want to consider not typedef'ing matrix. I imagine it's a struct, so it has a type already. You increase the complexity of the code with the typedef; and that's all you get for it.


One option is already mentioned - return type (void*). However i want to mention another not discussed option here- make return type Union, like so:

typedef union {
    int scalar;
    int* vector;
    int** matrix;
} custom_type;


custom_type* myFunction() {
// todo
}

Union is much like Struct except that Union members shares same memory, so only one member of all union members can be set/used at a time. But be careful - you must clearly know what to expect from function in exact situation (But i think the same warning applies to void* case).

cheers!

0

精彩评论

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