Search code examples
c++templatesvariadic-templates

Apply functions belonging to other classes through variadic templates


Say I have three classes, ClassA, ClassB, and ClassC. And all three of these classes have a function called updateValue(int). And then I have controller class called, Controller. Who's constructor is templated like the following:

class Controller
{
  public:
    template <class...Classes>
    Controller(Classes & ...classes); // maybe initialize a tuple?

    void setValues(int val)
    {
      // unpack whatever data structure and call each classes updateValue(int)
    }
  private:
    std::tuple<Classes...classes> packedClasses; // Not sure if this is good idea? This will not compile
};

As you can see, I want to be able to take the classes from some data structure, and call their functions. For example, in main I would have:

int main()
{
  ClassA A;
  ClassB B;
  ClassC C;

  Controller controller1(A,B);
  Controller controller2(A,C);
  Controller controller3(B,C);
  Controller controller4(A,B,C);

  controller4.setValues(20);

}

Each class has their own way of updating a value, for example ClassA has setValue(int), ClassB has setInt(int), and ClassC has updateNumber(int). My plan is to write the function updateValue into each of these classes that will call their setter functions. However, I am not sure how to achieve what it is I am trying to do. How can I unpack all of the classes and call their function updateValue(int)?


Solution

  • From your current interface, you might do something like:

    class Controller
    {
     public:
        template <class...Classes>
        Controller(Classes&... classes)
        {
            mF = [&](int val) { (classes.updateValue(val), ...); }; // Fold expression from C++17
        }
    
        void setValues(int val)
        {
            mF(val);
        }
        private:
            std::function<void(int)> mF;
        };