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

巧了我就是萌 提交于 2019-11-30 21:04:45

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?

You don't need a macro for this.

auto p = std::make_pair(2, 3);
int x, y;
std::tie(x, y) = p;

If you want references to existing members of a pair:

auto p = std::make_pair(2, 3);
auto& x = p.first;
auto& y = p.second;

That's it.

Now you can move on to something more challenging/interesting/important.

What you want is std::tie.

decltype(p.first) x;
decltype(p.second) y;
std::tie(x,y) = p;

If you want, you could even use that to define your macro. Note that this will only work for 2-tuples - if you want 3-tuples or more, you'll need to do it a bit differently. For example, if you have a 3-tuple t:

decltype(std::get<0>(t)) x;
decltype(std::get<1>(t)) y;
decltype(std::get<2>(t)) z;
std::tie(x,y,z) = t;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!