C++ MACRO,它将在该块之后执行代码块和某个命令

Pon*_*oni 2 c++ macros c-preprocessor

void main()
{
    int xyz = 123; // original value
    { // code block starts
        xyz++;
        if(xyz < 1000)
            xyz = 1;
    } // code block ends
    int original_value = xyz; // should be 123
}

void main()
{
    int xyz = 123; // original value
    MACRO_NAME(xyz = 123) // the macro takes the code code that should be executed at the end of the block.
    { // code block starts
        xyz++;
        if(xyz < 1000)
            xyz = 1;
    } // code block ends << how to make the macro execute the "xyz = 123" statement?
    int original_value = xyz; // should be 123
}
Run Code Online (Sandbox Code Playgroud)

只有第一个main()工作.
我认为这些评论解释了这个问题.

它不需要是一个宏,但对我来说,它听起来像一个经典的"宏需要"案例.

顺便说一下,有BOOST_FOREACH宏/库,我认为它与我想要实现的完全一样,但是对我来说找到我需要的本质太复杂了.
从其介绍性手册页中,举例:

#include <string>
#include <iostream>
#include <boost/foreach.hpp>

int main()
{
    std::string hello( "Hello, world!" );

    BOOST_FOREACH( char ch, hello )
    {
        std::cout << ch;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 8

最简洁的方法是使用RAII容器重置值:

// Assumes T's assignment does not throw
template <typename T> struct ResetValue
{
    ResetValue(T& o, T v) : object_(o), value_(v) { }
    ~ResetValue() { object_ = value_; }

    T& object_;
    T value_;
};
Run Code Online (Sandbox Code Playgroud)

用作:

{
    ResetValue<int> resetter(xyz, 123);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

当块结束时,将调用析构函数,将对象重置为指定值.

如果你真的想使用一个宏,只要它是一个相对简单的表达式,你可以使用for-block来做到这一点:

for (bool b = false; b == false; b = true, (xyz = 123))
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

哪个可以变成一个宏:

#define DO_AFTER_BLOCK(expr) \
    for (bool DO_AFTER_BLOCK_FLAG = false; \
         DO_AFTER_BLOCK_FLAG == false; \
         DO_AFTER_BLOCK_FLAG = true, (expr))
Run Code Online (Sandbox Code Playgroud)

用作:

DO_AFTER_BLOCK(xyz = 123)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我不认为宏观方法是个好主意; 如果我在生产源代码中看到这个,我可能会觉得很困惑.