簡體   English   中英

函數中的C ++宏和默認參數

[英]C++ macro and default arguments in function

我試圖創建一個通用函數來顯示錯誤消息,可能是在顯示消息后程序應該退出。

我希望該函數顯示發生錯誤的源文件和行。

參數列表:

1.char *desc //description of the error
2.char *file_name //source file from which the function has been called
3.u_int line //line at which the function has been called
4.bool bexit=false //true if the program should exit after displaying the error
5.int code=0 //exit code

因為(4)和(5)我需要在函數定義中使用默認參數,因為我不希望它們被指定,除非程序應該退出。

由於(2)和(3)我需要使用重定向到原始函數的宏,如下所示:

#define Error(desc, ???) _Error(desc,__FILE,__LINE__, ???)

問題是我看不出這兩個元素應該如何協同工作。

它應該如何顯示的示例:

if(!RegisterClassEx(&wndcls))
    Error("Failed to register class",true,1); //displays the error and exits with exit code 1

if(!p)
    Error("Invalid pointer"); //displays the error and continues

你不能在C99中重載宏 - 你需要兩個不同的宏。 使用C11,使用_Generic有一些希望。

我開發了一些非常相似的東西 - 一個用於Visual Studio的自定義警告生成器代碼段 - 使用宏。 GNU GCC具有一些與MSVS兼容的類似設置。

#define STR2(x) #x
#define STR1(x) STR2(x)
#define LOC __FILE__ “(“STR1(__LINE__)”) : Warning Msg: “
#define ERROR_BUILDER(x) printf(__FILE__ " (“STR1(__LINE__)”) : Error Msg: ” __FUNCTION__ ” requires ” #x)

上面的行處理你的參數1到3.添加對4的支持需要在宏中插入exit()調用。 此外,如果需要兩個不同的參數列表(具有默認參數的列表可以委托給另一個宏),則創建兩個不同的宏包裝器。

#define ERROR_AND_EXIT(msg, cond, errorcode) ERROR_BUILDER(msg) if (cond) exit(errorcode)
#define ERROR_AND_CONT(msg) ERROR_BUILDER(msg)

我在這里做了一個詳細的描述(警告:這是我的博客 - 所以認為它是一個無恥的插件)。

暫無
暫無

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

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