vector of function pointers
I'm trying to achieve the following:
(1) main() should not be modified by my user
(2) user provides a file (or files) containing functions all of the same type and same number and type of arguments, but the details of what the functions do are left to the user.
(3) main somehow gets a vector of pointers to those functions and the determination of which functions are called occurs at runtime.
I came up with the following dumb example of how I can accomplish this (the user would provide both funcs.h and func.cpp), but I'm wondering if there's a better way. I'm not thrilled with the idea of making the user include the array (funcArr) of function pointers, but I couldn't think of any other way to load main's funcs vector.
Code:
// fn_pointer.cpp
#include <iostream>
#include <vector>
#include "funcs.h"
using namespace std;
int main () {
vector<int (*)(int,int)> funcs(&(*funcArr), &(*funcArr)+NUM_FUNCS);
int x,y,op,sum;
cout << "1. add\n2. multiply\n\tChoose 1 or 2\n";
cin >> op;
cout << "enter 2 operands:\n";
cin >> x >> y;
sum = funcs[op-1](x,y);
cout << "the result is " << sum << "\n";
}
Code:
// funcs.h
#ifndef funcs_h_
#define funcs_h_
const int NUM_FUNCS = 2;
int add(int,int);
int mult(int,int);
int (*funcArr[])(int, int) = {add, mult};
#endif
Code:
// funcs.cpp
int add(int x, int y) {return x + y;}
int mult(int x, int y) {return x * y;}