[英]Is there any way to keep the return type of a function variable?
我想定義一個 function,根據 arguments,返回具有多個變體類型值的struct
或單個int *
,用戶通過命令行。
我知道,我可以總是簡單地返回一個struct
並從與用戶輸入數據相關的struct
中檢索特定值,但我想知道 state 是否有可能 function 將返回 A 或 B。
不,function 返回類型必須在編譯期間確定和修復,它不能在運行期間更改(即,基於用戶輸入)。
但是,您可以使用 function 指針數組來根據用戶輸入調用不同的函數。
可能最接近的方法是返回帶有附加類型信息的結構union
。
typedef struct {
MyType type;
int alpha;
float beta;
char * gamma;
} A;
typedef struct {
MyType type;
int * data;
} B;
typedef union {
MyType type;
A a;
B b;
} Returnable;
// Returnable func (void);
但是,您需要在 function 調用之前檢查 args 或在之后type
字段。 在后一種情況下,您失去了編譯時類型檢查並發明了運行時類型檢查,這很容易出錯。
正如@EricPostpischil 在評論中建議的那樣,還有一種方法:
typedef struct {
int foo;
} A;
typedef struct {
char bar;
} B;
typedef struct {
MyType data_type;
union {
A a;
B b;
} data;
} Returnable2;
IMO 最好在 C 中實現某種多態性
#define mul3(x) _Generic((x), \
double: mul3d, \
int: mul3i)(x)
int mul3i(const int x)
{
printf("Mul3 int %d * 3 = %d\n", x, x*2);
return x * 3;
}
double mul3d(const double x)
{
printf("Mul3 double %f * 3 = %f\n", x, x*2);
return x * 3;
}
int main()
{
mul3(5.0);
mul3(4);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.