简体   繁体   English

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

[英]Function-like macro and enumerator with the same name

In the following fragment I have a struct IndexError that I return when the user made an error using my library. 在下面的片段中,我有一个struct IndexError ,当用户使用我的库出错时返回该错误。 I have a function-like macro that casts a pointer to a IndexError* , and an enum, both called INDEX_ERROR . 我有一个类似于函数的宏,该宏将指针转换为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)

An example to how I would use this is: 我将如何使用此示例:

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

Then I check the status. 然后,我检查状态。 If it doesn't return SUCCESS , I would examine the error, because that should then point to a newly create error. 如果它没有返回SUCCESS ,那么我将检查该错误,因为这将指向一个新创建的错误。

The implementation of one of the array functions might look like this: 数组函数之一的实现可能如下所示:

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

So my question is, at the return INDEX_ERROR; 所以我的问题是, return INDEX_ERROR; , will the INDEX_ERROR return the value from the enum, or will the preprocessor bite me because my naming is inconvenient? INDEX_ERROR会从枚举中返回值,还是因为我的命名不便,预处理器会咬我吗?

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

It's the enumerator. 它是枚举数。 It can't be the result of expanding the function-like macro, because it isn't followed immediately by a left paren ( token, as the preprocessor requires 1 . 它不可能是扩展类似函数的宏的结果,因为它不会紧跟左括号(标记,因为预处理程序需要1)

It's slightly smelly, though. 不过,它有点臭。 Different names for the macro and the enumerator will make the code clearer and self evident without needing to read the fine print of the language specification. 宏和枚举器的不同名称将使代码更清晰,更清晰,而无需阅读语言规范的精巧版。


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" 1 - n1570 6.10.3p10 “每个类似函数的宏名称的后续实例,后跟一个(作为下一个预处理标记引入了在定义中被替换列表替换的预处理标记的序列”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM