c++ - How can I create a macro which uses a value multiple times, without copying it? -
i'd create macro unpacks pair 2 local variables. i'd not create copy of pair if it's variable, accomplish:
#define unpack_pair(v1, v2, pair) \ auto& v1 = pair.first; \ auto& v2 = pair.second; unpack_pair(one, two, x); however, i'd not evaluate expression it's given multiple times, e.g. should call expensive_computation() once:
unpack_pair(one, two, expensive_computation()); if do:
#define unpack_pair_a(v1, v2, pair) \ auto tmp = pair; \ auto& v1 = tmp.first; \ auto& v2 = tmp.second; then works expensive_computation() case, makes copy in x case. if do:
#define unpack_pair_r(v1, v2, pair) \ auto& tmp = pair; \ auto& v1 = tmp.first; \ auto& v2 = tmp.second; then works in x case without making copy fails in expensive_computation() case. if do:
#define unpack_pair_cr(v1, v2, pair) \ const auto& tmp = pair; \ auto& v1 = tmp.first; \ auto& v2 = tmp.second; #define unpack_pair_rr(v1, v2, pair) \ auto&& tmp = pair; \ auto& v1 = tmp.first; \ auto& v2 = tmp.second; these both compile , run, suspect invoke undefined behavior - correct that? also, either of these make sense?
#define unpack_pair_rr(v1, v2, pair) \ auto&& tmp = std::move(pair); \ auto& v1 = tmp.first; \ auto& v2 = tmp.second; #define unpack_pair_rr(v1, v2, pair) \ auto&& tmp = std::forward<decltype(pair)>(pair); \ auto& v1 = tmp.first; \ auto& v2 = tmp.second; is there way create macro works both of these use cases - not copying x yet not invoking undefined behavior when given result of expression or function call?
auto&& creates forwarding reference, i.e. accepts anything. not (always) create rvalue reference. this:
#define unpack_pair(v1, v2, pair) \ auto&& tmp = pair; \ auto& v1 = tmp.first; \ auto& v2 = tmp.second; however, suggest against (unless scope of use of unpack_pair limited , operation really ubiquitous in scope). looks obscurity no real benefit me. imagine returning project after 6 months, 2 hours find critical bug. thanking using nonstandard macro-based syntax instead of readable?
Comments
Post a Comment