简体   繁体   English

如何使用宏在函数中放置代码?

[英]How can I place code in a function using macros?

Let's say I have a function 假设我有一个功能

void foo()
{
    foo1();
}

I want to have a macro that I can use in other place like that: 我想要一个可以在其他地方使用的宏:

ADD_FUNCTION_TO_FOO(foo2());

So the function foo() will look like that for the compiler: 因此,函数foo()对于编译器将如下所示:

void foo()
{
    foo1();
    foo2();
}

Is that possible to achieve? 那有可能实现吗? Or perhaps is there other way around that? 还是有其他解决方法?

You can't modify a function. 您无法修改功能。 The definition of foo() is exactly what it does, forever. foo()的定义永远就是它所做的。

But you could write foo to be extensible in the first place: 但是您可以首先将foo写成可扩展的:

#include <functional>
#include <vector>
#include <iostream>

std::vector<std::function<void()>> extra_callbacks_for_foo;

void foo1();

void foo()
{
    foo1();
    for (auto& cb : extra_callbacks_for_foo)
        cb();
}

#define ADD_FUNCTION_TO_FOO(expr) \
  (extra_callbacks_for_foo.push_back([&]() { (expr); }))

See the working example on coliru . 请参阅coliru上工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM