具有相同名称的类似函数的宏和枚举器

Function-like macro and enumerator with the same name

在下面的片段中,我有一个 struct IndexError return 当用户在使用我的库时出错。我有一个类似于函数的宏,它将一个指针转换为 IndexError* 和一个枚举,两者都称为 INDEX_ERROR.

enum errors {
    SUCCESS,
    INVALID_ARGUMENT,
    INDEX_ERROR
};

struct Error {
    char error_buff[BUFSIZ];
};

typedef struct Error Error;

struct IndexError {
    Error  parent;
    size_t invalid_index;
    // etc.
};

typedef struct IndexError IndexError;


#define INDEX_ERROR(obj) ((IndexError*) obj)

我将如何使用它的一个例子是:

size_t pos = 4;
int IndexPointer* error = NULL;
int status = array_remove_item(my_array, pos, &error);

然后我查看状态。如果它没有 return SUCCESS,我会检查错误,因为那应该指向一个新创建的错误。

其中一个数组函数的实现可能如下所示:

int array_remove_item(Array* array, size_t pos, Error** error_out)
{
    Error* error = NULL;
    if(pos >= array->size) {
        index_error_create(INDEX_ERROR(&error), pos); // use casting macro.
        *error_out = error;
        return INDEX_ERROR; // is this the macro or the value from the errors enum?
    }
    priv_array_remove_item(array, pos);
    return SUCCESS;
}

所以我的问题是,在 return INDEX_ERROR;INDEX_ERROR return 是枚举中的值,还是预处理器会因为我的命名不方便而咬我?

return INDEX_ERROR; // is this the macro or the value from the errors enum?

这是枚举器。它不可能是扩展类函数宏的结果,因为它没有紧跟左括号 ( 标记,因为预处理器需要 1.

不过有点臭。宏和枚举器的不同名称将使代码更清晰和不言自明,而无需阅读语言规范的细则。


1 - n1570 6.10.3p10 "Each subsequent instance of the function-like macro name followed by a ( as the next preprocessing token introduces the sequence of preprocessing tokens that is replaced by the replacement list in the definition"