How can I create a macro which uses a value multiple times, without copying it?

前端 未结 3 1065
北海茫月
北海茫月 2021-01-05 19:20

I\'d like to create a macro which unpacks a pair into two local variables. I\'d like to not create a copy of the pair if it\'s just a variable, which this would accomplish:<

3条回答
  •  礼貌的吻别
    2021-01-05 19:37

    auto&& creates a forwarding reference, i.e. it accepts anything. It does not (always) create an rvalue reference. So just do this:

    #define UNPACK_PAIR(V1, V2, PAIR) \
        auto&& tmp = PAIR; \
        auto& V1 = tmp.first; \
        auto& V2 = tmp.second;
    

    However, I would strongly suggest against this (unless the scope of the use of UNPACK_PAIR is very limited and the operation is really ubiquitous in that scope). It looks like obscurity for no real benefit to me. Imagine returning to the project after 6 months, with just two hours to find a critical bug. Will you be thanking yourself for using a nonstandard macro-based syntax instead of something readable?

提交回复
热议问题