包含 return 的 C++ 宏表达式(就像 Rust 的 try!)

标签 c++ macros

Rust 有一个宏,它是一个表达式,可以计算出某个值,或者从函数返回。有没有办法在 C++ 中做到这一点?

像这样:

struct Result
{
    bool ok;
    int value;
}

Result foo() { ... }

#define TRY(x) (auto& ref = (x), ref.ok ? ref.value : return -1)

int main()
{
    int i = TRY(foo());
}

不幸的是,它不起作用,因为 return 是一个语句而不是表达式。上面的代码还有其他问题,但它大致说明了我想要什么。有没有人有什么好主意?

最佳答案

感谢 NathanOliver 的 link看起来你可以用 statement expressions 来做显然只有 Clang 和 GCC 支持。像这样:

#define TRY(x)                                                     \
    ({                                                             \
        auto& ref = (x);                                           \
        if (!ref.ok) {                                             \
            return -1;                                             \
        }                                                          \
        ref.value; // The block evaluates to the last expression.  \
    })

关于包含 return 的 C++ 宏表达式(就像 Rust 的 try!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43117219/

相关文章:

c++ - delete 如何处理指针常量?

c++ - 如何将返回类型声明为模板类型名的内部类?

c++ - 什么是智能指针,我应该什么时候使用它?

C++/OpenCV - 使用 flann::index 后如何获取我的图像? (与 BoF)

c - 如何对字符串使用 switch 和 case

function - 在 dolist 中扩展宏

c++ - 使用指针调用 C++ DLL 函数

c - 从宏的内容定义宏

generics - 在 Rust 中使用宏创建 impl-block 的问题

c++ - 宏中的宏