-4

I am trying to implement a class which could store several functions and evaluate all of them sequentially in the order they are added. The goal would be instantiate an object of this class like that:

f_int f1 = f_int {p1, p2, p3};

where p1, p2 and p3 are functions like that: int p1(int x) { return ...; }. After added some functions to this object, I could evaluate all of them calling:

std::cout << f1(3) << std::endl;

the implementations should work with functions of 1, 2, 3 or more variables, but right now this is not happening.

also, I wonder if there is a way to not have the second declaration of type in f_int f1 = f_int {p1, p2, p3}; (using only f_int f1 = {p1, p2, p3};). and if is possible, I would like to declare how many variables the program should accept, with something like that (or close to that): f_int f1('x') or f_float f1('x', 'y').

at last, would be great if instead of declare each function like the example above, by its name p1 or p2, I would have something more like:

f1('x') = {'x'*'x', 2*'x', 8}

maybe using something like a lambda or macros? I don't have much experience about this to be sure if any of this would be possible.

Anyway, the implementation for the class I have right now, which as I mentioned it's working for function with 1 argument only, looks like that right now:

template<typename T, typename ... Args>
class Function {
private:
  std::vector<std::function<T(T,Args...)>> terms;
public:
  Function(std::initializer_list<std::function<T(T,Args...)>> array) {
    for(long unsigned int i=0; i<array.size(); i++) terms.push_back(std::data(array)[i]);
  }

  T operator()(T t, Args ... args) {
    T result = 0;
    for(long unsigned int i=0; i<terms.size(); i++) result += terms[i](t,args...);
    return result;
  }

  Function<T>& operator=(std::initializer_list<std::function<T(T,Args...)>> array) {
    for(long unsigned int i=0; i<array.size(); i++) terms.push_back(std::data(array)[i]);
    return *this;
  }
};

typedef Function<int> f_int;
typedef Function<float> f_float;
typedef Function<double> f_double;

Anyone can tell me hints if any of this is possible and, if so, give any hints of how to modify the class above to implement that?

New contributor
Kleber Mota is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • It actually works. You're just one tiny step from using it correctly. Just specify multiple types when you typedef (instantiate) the Function template, as in Function<int, char, char>. Example: godbolt.org/z/5hGvcrbvq
    – rwong
    Jun 19 at 1:54

0

Browse other questions tagged or ask your own question.