Jump to content

Recommended Posts

Posted

 Estou tentando implementar para um projeto uma classe que guarda um vetor de ponteiros para funções, e executa essas funções de uma vez quando um método da classe é invocado. Essas funções podem ter 1 ou mais argumentos, mas no momento a classe só funciona quando eu uso funções que tenham apenas 1 argumento.

A implementação da classe que eu tenho no momento seria essa:

 

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;

 

Um código de teste para essa classe seria esse:

int p1(int x) {
  return x*x;
}

int p2(int x) {
  return x;
}

int p3(int x) {
  return 2;
}

int p4(int x, int y) {
  return x*x * 2*y*y;
}

int p5(int x, int y) {
  return 2*x*x + y*y;
}

float p6(float x) {
  return  x*x;
}

float p7(float x) {
  return  1.5f;
}

double p8(double x) {
  return x*x*x;
}

double p9(double x) {
  return -1.565*x*x;
}

double p10(double x) {
  return 17.515;
}

int main(int argc, char ** argv) {
  //std::function f_1(p4), f_2(p5);
  //std::cout << f_1(3,2) << std::endl;
  //std::cout << f_2(3,2) << std::endl;

  f_int f1 = f_int {p1, p2, p3};
  f_float f2 = f_float {p6, p7};
  f_double f3 = f_double {p8, p9, p10};
  std::cout << f1(-2) << std::endl;
  std::cout << f2(3.5f) << std::endl;
  std::cout << f3(-2.185) << std::endl;
  return 0;
}

Alguém conseguiria dar uma dica de como alterar a classe para que ela funcione com funções de mais de 1 argumento? Por exemplo, com as funções p4 e p5 do exemplo.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...