[英]How to implement C macro with assert
我在一個 C 項目上工作,它通過使用宏實現了一種多態性
void method1Instrumentation(void*);
bool method2Instrumentation(void*);
bool method3Instrumentation(void*);
#define method1(arg) method1Instrumentation(arg)
#define method2(arg) method2Instrumentation(arg)
#define method3(arg) method32Instrumentation(arg)
對於method1Instrumentation, method2Instrumentation, method3Instrumentation
每一個,都有幾種實現。 根據內部配置,編譯器“選擇”適當的函數。 我(可能)無法改變給定的設計。 但我需要向method*
添加asserts
。
工作正常
#define method1(arg) assert(arg == NULL) method1Instrumentation(arg)
不起作用(編譯問題)
#define method2(arg) assert(arg == null) method2Instrumentation(arg)
出現問題是因為原始代碼有以下調用
if(method2(arg))
{
}
我應該如何按照我的限制添加assets
?
使用逗號運算符將assert
和函數調用組合到一個表達式中。 此外,將其括在括號中以防止在將其與其他運算符組合時出現運算符優先級問題。
#define method1(arg) (assert(arg != NULL), method1Instrumentation(arg))
為了稍微反對宏觀丑陋,我會建議以下幾點:
如評論中指出的那樣編輯為使用 assert() ;
#include <stdio.h>
#include <stdbool.h>
bool method1( void* data );
bool method2( void* data );
typedef bool (*methodPointer)(void*);
bool assertAndCall( void* data, methodPointer );
#define call1( arg ) assertAndCall( arg, method1 )
#define call2( arg ) assertAndCall( arg, method2 )
bool method1( void* data )
{
printf("method1\n");
}
bool method2(void* data )
{
printf("method2\n");
}
bool assertAndCall( void* data, methodPointer mp )
{
assert( arg == null );
mp( data );
}
int main()
{
call1( "test ");
call2( "test" );
call1( NULL );
return 0;
}
我知道,仍然有很多宏並且有更好的解決方案,但我想玩,,,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.