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

后端 未结 17 875
傲寒
傲寒 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条回答
  •  猫巷女王i
    2020-12-06 05:19

    with (OBJECT) {CODE}
    

    There is no such thing in C++.
    You can put CODE as is into a method of OBJECT, but it is not always desirable.

    With C++11 you can get quite close by creating alias with short name for OBJECT.
    For example code given in question it will look like so:

    {
        auto &_ = *pointer;
        if (_.field1 && ... && _.fieldn) {...}
    }
    

    (The surrounding curly braces are used to limit visibility of alias _ )

    If you use some field very often you can alias it directly:

    auto &field = pointer->field;
    // Even shorter alias:
    auto &_ = pointer->busy_field;
    

提交回复
热议问题