通过可变参数模板应用属于其他类的函数 [英] Apply functions belonging to other classes through variadic templates
问题描述
假设我有三个类,ClassA
、ClassB
和 ClassC
.所有这三个类都有一个名为 updateValue(int)
的函数.然后我将控制器类称为 Controller
.Who 的构造函数的模板如下:
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);
}
每个类都有自己的更新值的方式,例如ClassA
有setValue(int)
,ClassB
有setInt(int)
,而 ClassC
有 updateNumber(int)
.我的计划是将函数 updateValue
写入每个将调用它们的 setter 函数的类中.但是,我不确定如何实现我正在尝试做的事情.如何解压所有类并调用它们的函数 updateValue(int)
?
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)
?
推荐答案
从您当前的界面,您可能会执行以下操作:
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;
};
这篇关于通过可变参数模板应用属于其他类的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!