c++ - 用于调用一系列具有相似名称(即 f_0、f_1、f_2、...)的宏生成函数的宏
问题描述
我遇到了一个非常特殊的问题,目前我不知道如何解决它。
我正在使用以下宏块来生成具有相似名称的函数:
#define CONCAT_IMPLEMENTATION(arg1, arg2) arg1 ## arg2
#define CONCAT(arg1, arg2) CONCAT_IMPLEMENTATION(arg1, arg2)
#define UNIQUE_FUNCTION_NAME(index) CONCAT(f_, index)
#define GENERATE_FUNCTION() void UNIQUE_FUNCTION_NAME(__COUNTER__) ()
所以这样的代码:
GENERATE_FUNCTION()
{
std::cout << "first function" << std::endl;
}
GENERATE_FUNCTION()
{
std::cout << "second function" << std::endl;
}
替换为:
void f_0 ()
{
std::cout << "first function" << std::endl;
}
void f_1 ()
{
std::cout << "second function" << std::endl;
}
有没有办法实现一个宏或一个函数来调用所有生成的函数?也就是说它会调用从f_0到f_N的函数,其中N是__COUNTER__
宏的当前值。
像这样的东西:
#define RUN_ALL_GENERATED_FUNCTIONS() // ??? //
int main()
{
RUN_ALL_GENERATED_FUNCTIONS();
return 0;
}
在我看来是不可能的。请给我一些建议好吗?
解决方案
这里不需要宏,只需将函数指针推入向量中,然后您可以遍历向量依次调用每个函数。一种可能的实现是:
#include <vector>
#include <functional>
#include <iostream>
struct Functions
{
static std::vector<std::function<void()>> functions;
template <typename T>
static T make_function(T f)
{
functions.push_back(f);
return f;
}
static void call()
{
for (auto& f : functions)
{
f();
}
}
};
std::vector<std::function<void()>> Functions::functions;
auto f_1 = Functions::make_function([]
{
std::cout << "first function" << std::endl;
});
auto f_2 = Functions::make_function([]
{
std::cout << "second function" << std::endl;
});
int main()
{
f_1();
f_2();
Functions::call();
}
如果你真的需要,你仍然可以包装Functions::make_function
成一个宏。
推荐阅读
- java - 安装 Apache POI 时遇到问题
- kotlin - 从 InputStream 中读取的挂起函数
- android - 我是否需要迁移才能将类型 Int 更改为 Long?
- c - 在这个 C 代码中 goto 语句是不可避免的吗?
- zipline - zipline :更改内置因素的输入数据
- r - 使用 ggplot 创建条形图
- c# - C# dotnet run 保持失败:错误:无法加载源的服务索引
- r - 相交两个 shapefile 后:`vapply 中的错误(g2,st_is_empty,logical(1))`
- amazon-web-services - AWS - 如何将保存的环境配置从一个应用程序加载到另一个应用程序
- python - 从我的 python 脚本在集群上加载环境模块