相关疑难解决方法(0)

如何创建一个多次使用值的宏,而不复制它?

我想创建一个宏,将一对解包为两个局部变量.如果它只是一个变量,我想不创建该对的副本,这将实现:

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

UNPACK_PAIR(one, two, x);
Run Code Online (Sandbox Code Playgroud)

但是,我也希望它不要评估多次给出的表达式,例如这应该只调用expensive_computation()一次:

UNPACK_PAIR(one, two, expensive_computation());
Run Code Online (Sandbox Code Playgroud)

如果我做:

#define UNPACK_PAIR_A(V1, V2, PAIR) \
    auto tmp = PAIR; \
    auto& V1 = tmp.first; \
    auto& V2 = tmp.second;
Run Code Online (Sandbox Code Playgroud)

然后它适用于expensive_computation()案例,但它在x案件中复制.如果我做:

#define UNPACK_PAIR_R(V1, V2, PAIR) \
    auto& tmp = PAIR; \
    auto& V1 = tmp.first; \
    auto& V2 = tmp.second;
Run Code Online (Sandbox Code Playgroud)

然后它在x没有复制的情况下工作,但在这种expensive_computation()情况下失败.如果我做:

#define UNPACK_PAIR_CR(V1, V2, PAIR) \
    const auto& …
Run Code Online (Sandbox Code Playgroud)

c++ macros undefined-behavior c++11 forwarding-reference

5
推荐指数
2
解决办法
242
查看次数