C++:如何在循环中为函数指针生成数组

标签 c++ arrays function pointers

给定

// from an external C api
void f(int i, void (*g)());

const int n = ...
void a0(); void a1(); ...
void (*a[n])();

int main()
{
  a[0] = a0; a[1] = a1; ...
  for (int i = 0; i != n; ++i)
    f(i, a[i]);
  ...
}

我不想生成每个函数 a0a1,...并将其分别分配给 a。相反,我想生成函数并将它们分配给循环中的 a,类似这样的事情(抱歉,代码很丑,它不会编译):

for (int i = 0; i != n; ++i)
{
    void b() { cout << i; };
    a[i] = b;
}

这可能吗?我该怎么做?

最佳答案

像这样尝试:

#include <iostream>
#include <vector>
using namespace std;

// from an external C api
void f(int i, void(*g)())
{
    //g();
}

const int n = 100;
using fnType = void(*)();
vector<fnType> a(n);

template <int N>
void func()
{
    cout << N << endl;
}

template <int N>
void init()
{
    a[N - 1] = func<N - 1>;
    init<N - 1>();
}

template <>
void init<0>()
{
}


int main()
{
    init<n>();

    for(int i = 0; i < n; ++i)
        a[i]();
    for(int i = 0; i < n; ++i)
        f(i, a[i]);   
}

另外,你可以定义

vector<std::function<void()>> funcs(n);

并从 f 调用它:

template <int N>
void func()
{
    //cout << N << endl;
    funcs[N]();
}

所以,你可以简单地定义它:

for(int k = 0;k < n;k++)
    funcs[k] = [k](){cout << k << endl;};

关于C++:如何在循环中为函数指针生成数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53494939/

相关文章:

c - 如何正确传递这个 C 字符串数组?

wordpress - 默认情况下使您的帖子受密码保护

c++ - 什么是测试文件以查看其是否为 zip 文件的好方法?

android - Cocos2dx 安卓构建错误: "arm-linux-androideabi-g++: No such file or directory"

arrays - 错误#6366 : The shapes of the array expressions do not conform

c# - 如何返回 C# 对象而不是数组 JSON

javascript - 将变量插入innerHTML

python - Python 中的全局变量和局部变量

c++ - 通过强制转换 nullptr 获取成员变量的偏移量

c++ - 将二维数组传递给函数 C++