jeudi 6 octobre 2016

dynamic execution of a specific function

class Obj
{
   public:
     void func1(int n) {}
     void func2(std:string n) {}
};

std::vector<Obj> retrieveObjs()
{
    std::vector<Obj> result;
    // ...
    return result;
}

int main()
{
    {
      auto objs = retrieveObjs();  
      for (auto& obj : objs)       
      {
         obj.func1(100);
      }
    }

    {
      auto objs = retrieveObjs();  
      for (auto& obj : objs)       
      {
         obj.func2("xxx");
      }
    }
    return 0;
}

I would like to have a generic function to invoke specific function from all objs like the following pseudocode.

void invokeAll(FUNCTION f, PARAM p)   // pseudocode
{
   auto objs = retrieveObjs();
   for (auto& obj : objs)       
   {
     obj.f(p); 
   }
}

int main() // pseudocode
{
    invokeAll(func1, 100);
    invokeAll(func2, "xxx");
}

Is that possible with template/lambda/for_each or similar tricks to do that?

Aucun commentaire:

Enregistrer un commentaire