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

后端 未结 17 848
傲寒
傲寒 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条回答
  •  Happy的楠姐
    2020-12-06 05:28

    Probably the closest you can get is this: (Please don't downvote me; this is just an academic exercise. Of course, you can't use any local variables in the body of these artificial with blocks!)

    struct Bar {
        int field;
    };
    
    void foo( Bar &b ) {
        struct withbar : Bar { void operator()() {
            cerr << field << endl;
        }}; static_cast(b)();
    }
    

    Or, a bit more demonically,

    #define WITH(T) do { struct WITH : T { void operator()() {
    #define ENDWITH(X) }}; static_cast((X))(); } while(0)
    
    struct Bar {
        int field;
    };
    
    void foo( Bar &b ) {
        if ( 1+1 == 2 )
            WITH( Bar )
                cerr << field << endl;
            ENDWITH( b );
    }
    

    or in C++0x

    #define WITH(X) do { auto P = &X; \
     struct WITH : typename decay< decltype(X) >::type { void operator()() {
    #define ENDWITH }}; static_cast((*P))(); } while(0)
    
            WITH( b )
                cerr << field << endl;
            ENDWITH;
    

提交回复
热议问题