我将我的方法从my original question更改为对整个类进行模板化,然后将其放在可变的元组中。现在,我可以像我希望的那样使用getter和setter方法。但是,现在我正在尝试将其向前推进,并将各个控制器组合为一个控制器。
#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
通过此操作,我可以执行以下操作:
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);
但是,我想更进一步,将两者结合起来,像这样:
Controller master(controller1,controller2,controller3);
master.setValues(40);
我看过at this post talking about joining variadic templates,但是我认为这返回的是类型(?)而不是类。我也尝试创建两个重载类,但是我认为我没有正确创建重载:
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
};
如何将任意数量的模板化可变参数模板化类合并为一个类?我确实有能力使用C ++ 17。
答案 0 :(得分:4)
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 );
}
...
给予我们
Controller master = controller1+controller2+controller3;
master.setValues(40);