initialize Vector of function pointer

815 Views Asked by At

Could someone tell me how to initialize Vector of function pointer.`

void a(){cout << "godzilla_1";}
void b(){cout << "godzilla_2";}
void c(){cout << "godzilla_3";}
void d(){cout << "godzilla_4";}

    vector<void(*)()> funcs = {a, b, c, d};

This gives me an error. in C++98 you can't initialize like this.

please give me a simple example.

3

There are 3 best solutions below

0
On

You may not use initialiser lists before c++11. The following will work

#include <iostream>
#include <vector>

void a(){std::cout << "godzilla_1";}
void b(){std::cout << "godzilla_2";}
void c(){std::cout << "godzilla_3";}
void d(){std::cout << "godzilla_4";}
int main() {

  std::vector<void(*)()> funcs;
  funcs.push_back(a);
  funcs.push_back(b);
  funcs.push_back(c);
  funcs.push_back(d);
  funcs.front()();
  return 0;
}
0
On

C++98:

funcs.push_back(a);
funcs.push_back(b);
funcs.push_back(c);
funcs.push_back(d);
0
On

You best bet is to use an array:

void (*funcs[])() = {a, b, c, d};