简体   繁体   中英

How to combine multiple variadic templated tuple classes into one class?

I have changed my approach from my original question to templatize the entire class instead and place it inside a variadic tuple. I can now use getters and setters the way that I would like them to be created. However, now I am trying to take it a step forward and combine the individual controllers into one controller.

#ifndef CONTROLLER_HPP
#define CONTROLLER_HPP

#include <functional>
#include <vector>
#include <iostream>
#include <utility>

template<typename...Classes>
class Controller
{
  public:
    Controller(Classes&...objects) : objects(objects...){}

    void setValues(int value)
    {
      std::apply([&](auto&...x) { (x.updateValue(value),...);}, objects);
    }

    void getValues(std::vector<int> &values)
    {
      std::apply([&](auto&...x) { (values.push_back(x.get()),...);}, objects);
    }
  private:
    std::tuple<Classes&...> objects;
};

#endif

With this I can do the following:

classA A;
classB B;
classC C;
classD D;
classE E;
classF F;
classG G;

Controller controller1(A,B,C);
Controller controller2(D,E);
Controller controller3(F,G);

controller1.setValues(20);
controller2.setValues(13);
controlelr3.setValues(32);

However, I want to take it a step further and combine the two like so:

Controller master(controller1,controller2,controller3);
master.setValues(40);

I have looked at this post talking about joining variadic templates , however I think this returns a type(?) and not a class. I also tried creating two overloaded classes, however I don't think I am creating the overload correctly:

template<typename...Classes>
class Controller
{
  public:
    Controller(Classes&...objects) : objects(objects...){}

    void setValues(int value)
    {
      std::apply([&](auto&...x) { (x.updateValue(value),...);}, objects);
    }

    void getValues(std::vector<int> &values)
    {
      std::apply([&](auto&...x) { (values.push_back(x.get()),...);}, objects);
    }
  private:
    std::tuple<Classes&...> objects;
};

template<Controller<typename ... > class Controllers, typename ...Classes>
class Controller<Controllers<Classes&...classes>...>
{
  // create a new controller that takes all the combined classes
};

How can I combine any number of templated variadic templated classes into one class? I do have the ability to use C++17.

template<typename...Classes>
class Controller
{
  Controller( std::tuple<Classes&...> tup ):objects(tup) {}
public:
  template<class...Rhs>
  Controller<Classes..., Rhs...> operator+( Controller<Rhs...> rhs ) const {
    return std::tuple_cat( objects, rhs.objects );
  }

...

giving us:

Controller master = controller1+controller2+controller3;
master.setValues(40);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM