Does C++ have “with” keyword like Pascal?

后端 未结 17 890
傲寒
傲寒 2020-12-06 05:02

with keyword in Pascal can be use to quick access the field of a record. Anybody knows if C++ has anything similar to that?

Ex: I have a pointer with m

17条回答
  •  广开言路
    2020-12-06 05:10

    No, there is no with keyword in C/C++.

    But you can add it with some preprocessor code:

    /* Copyright (C) 2018 Piotr Henryk Dabrowski, Creative Commons CC-BY 3.0 */
    
    #define __M2(zero, a1, a2, macro, ...) macro
    
    #define __with2(object, as) \
        for (typeof(object) &as = (object), *__i = 0; __i < (void*)1; ++__i)
    
    #define __with1(object) __with2(object, it)
    
    #define with(...) \
        __M2(0, ##__VA_ARGS__, __with2(__VA_ARGS__), __with1(__VA_ARGS__))
    

    Usage:

    with (someVeryLongObjectNameOrGetterResultOrWhatever) {
        if (it)
            it->...
        ...
    }
    
    with (someVeryLongObjectNameOrGetterResultOrWhatever, myObject) {
        if (myObject)
            myObject->...
        ...
    }
    

    Simplified unoverloaded definitions (choose one):

    unnamed (Kotlin style it):

    #define with(object) \
        for (typeof(object) &it = (object), *__i = 0; __i < (void*)1; ++__i)
    

    named:

    #define with(object, as) \
        for (typeof(object) &as = (object), *__i = 0; __i < (void*)1; ++__i)
    

    Of course the for loop always has only a single pass and will be optimized out by the compiler.

提交回复
热议问题