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

后端 未结 17 853
傲寒
傲寒 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:08

    The following approach relies on Boost. If your compiler supports C++0x's auto then you can use that and get rid of the Boost dependence.

    Disclaimer: please don't do this in any code that must be maintained or read by someone else (or even by yourself in a few months):

    #define WITH(src_var)                                             \
        if(int cnt_ = 1)                                              \
            for(BOOST_AUTO(const & _, src_var); cnt_; --cnt_)
    
    
    int main()
    {
        std::string str = "foo";
    
        // Multiple statement block
        WITH(str)
        {
            int i = _.length();
            std::cout << i << "\n";
        }
    
        // Single statement block
        WITH(str)
            std::cout << _ << "\n";
    
        // Nesting
        WITH(str)
        {
            std::string another("bar");
            WITH(another)
                assert(_ == "bar");
        }
    }
    

提交回复
热议问题