在C(而不是C++)中是否有可能使用一個泛型值(不是指針),設置了-pedantic和-wall -werror標誌的函數指針。C泛型參數轉換爲函數指針
注意:我無法更改參數類型。該代碼必須支持uint8_t,uint16_t等...類型作爲參數
目標:解決代碼問題。
問題
有沒有辦法來強制轉換一個uint8_t(和/或uint16_t)參數爲void *(Approach1)? 專門用於將非指針類型值傳遞給void *值。
有沒有辦法設置一個通用類型,可以處理所有不同的值(方法2)?
不得已 有沒有一種方法來在代碼中設置一個特定的編譯器異常?(this question has been answer)
方法1(導致從uint8_t一個無效的轉換到void *)
typedef struct
{
void (*set_func)(void*);
} SetFunction;
void setValue(uint8_t byteValue)//Not a pointer parameter
{
byteValue++;
}
void setShortValue(uint16_t byteValue)//Not a pointer parameter
{
byteValue++;
}
int main()
{
uint8_t a = 123;
uint16_t b = 321;
SetFunction pointerFuncion;
SetFunction pointerFuncionShort;
//Typecast the setValue to appease compiler warning
pointerFunction.set_func = (void(*)(void*))&setValue;
pointerFuncionShort.set_func = (void(*)(void*))&setShortValue;
//use the function pointer with non-pointer parameter
// Compile ERROR thrown invalid conversion from uint8_t to void*
pointerFunction.set_func(a);
pointerFuncionShort.set_func(b);
}
Aprroach 2(導致太多參數編譯錯誤)
typedef struct
{
void (*set_func)();//Blank parameter to allow multiple args
} SetFunction;
void setValue(uint8_t byteValue)//Not a pointer parameter
{
byteValue++;
}
void setShortValue(uint16_t byteValue)//Not a pointer parameter
{
byteValue++;
}
int main()
{
uint8_t a = 123;
uint16_t b = 321;
SetFunction pointerFuncion;
SetFunction pointerFuncionShort;
//Typecast the setValue to appease compiler warning
pointerFunction.set_func = (void(*)())&setValue;
pointerFuncionShort.set_func = (void(*)())&setShortValue;
//use the function pointer with non-pointer parameter
pointerFunction.set_func(a);// Compile ERROR thrown "Too many Args"
pointerFuncionShort.set_func(b);// Compile ERROR thrown "Too many Args"
}
UPDATE
爲了增加問題的清晰度。 我有100個具有1個參數的函數。 函數的1參數是不同的類型。 我不能更改任何函數,但我想要有1個函數指針類型(或更多基於類型)的任何函數。 我可以將任何與函數指針和類型關聯的類型更改爲函數指針,但不能指向它所指向的類型。
「不是指針」 - 爲什麼不呢?這正是你如何去做的; '無效*'。 –
只有在絕對需要的情況下,您才應繞過編譯器的類型檢查。現在大多數時候,有更好的方法。請記住:編譯器是您的自由人,您顯然也會因爲某種原因啓用警告。 – Olaf
@Ed S.函數指針是指向數百個現有函數的指針,我不能更改這些函數的參數,但是我可以改變函數指針的結構 – Ashitakalax