如何用assert实现C宏

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 都有几种实现。根据内部配置,编译"chooses"相应的函数。 我(可能)无法更改给定的设计。 但是我需要将 asserts 添加到 method*.

工作正常

#define method1(arg) assert(arg == NULL) method1Instrumentation(arg)

不起作用(编译问题)

#define method2(arg) assert(arg == null) method2Instrumentation(arg)

问题出现是因为原代码有如下调用

if(method2(arg))
{
}

根据我的限制,我应该如何添加 assets

使用 comma operatorassert 和函数调用组合成一个表达式。此外,将其括在括号中以防止在将其与其他运算符组合时出现运算符优先级问题。

#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;
}

我知道,还有很多宏,还有更好的解决方案,但我想玩,,