首页 > 解决方案 > 用于调用一系列具有相似名称(即 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_0f_N的函数,其中N__COUNTER__宏的当前值。
像这样的东西:

#define RUN_ALL_GENERATED_FUNCTIONS() // ??? //

int main()
{
    RUN_ALL_GENERATED_FUNCTIONS();
    return 0;
}

在我看来是不可能的。请给我一些建议好吗?

标签: c++c-preprocessor

解决方案


这里不需要宏,只需将函数指针推入向量中,然后您可以遍历向量依次调用每个函数。一种可能的实现是:

#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成一个宏。


推荐阅读