In my C++ programme, I often need to build a vector of values of a function on all the possible values of its arguments over some small finite field. For example, something like this:
int q = 7;
vector<int> GFq;
for (int x = 0; x < q; x++) GFq.push_back(x);
auto P = [q](int x, int y) -> int { return (x*x+y) % q; };
auto Q = [q](int x, int y) -> int { return (x+2*y) % q; };
auto f = [q,P,Q](int x1, int y1, int x2, int y2)
-> int {return (P(x1,y1) + Q(x2,y2)) % q; }
vector<int> table;
for (int x1: GFq) for (int y1: GFq) for (int x2: GFq) for (int y2: GFq)
table.push_back(f(x1,y1,x2,y2));
This pattern is so often repeated in my code that I naturally want to make it a function. So I need something like this:
template<typename F> // not sure if I need to use templates
vector<int> tabulate(int q, F f) {
// run through values 0..q-1 for all arguments of f
// and store the values of f to the resulting vector
}
Some questions/issues:
- I want to be able to pass an arbitrary function to
tabulate()
including those of different arity (i.e.f(x)
,f(x,y)
, etc.) - I want to construct the function I pass "on the fly", including usage of other functions (the same way as
f
is constructed fromP
andQ
in the first code snippet - if I manage to pass such a function, how can I run a loop over all possible arguments of
f
(i.e.0..q-1
for each of its arguments) insidetabulate()
?