如何在一个构造函数中使用两个可变参数来绑定两个函数?
问题描述:
我想构建传递两个函数与可变参数数目的参数对象:如何在一个构造函数中使用两个可变参数来绑定两个函数?
class PhaseSetControlProperty : public ControlProperty {
public:
template<typename FuncKicked, typename... ArgsKicked, typename FuncActivated, typename... ArgsActivated>
PhaseSetControlProperty(const std::vector<std::string> &kickedPhaseNames, const std::vector<std::string> &activatedPhaseNames, FuncKicked funcKicked, ArgsKicked ...argsKicked, FuncActivated funcActivated, ArgsActivated... argsActivated): ControlProperty("PhaseSetControl")
{
getModel()->addProperty(new StringListProperty("kickedPhaseNames", kickedPhaseNames));
getModel()->addProperty(new StringListProperty("activePhaseNames", activatedPhaseNames));
getModel()->addProperty(new StringListProperty("activated", activatedPhaseNames, funcActivated, argsActivated...));
getModel()->addProperty(new StringListProperty("kicked", kickedPhaseNames, funcKicked, argsKicked...));
}
};
实例化看起来是这样的:
model->addProperty(new PhaseSetControlProperty(kickedphasenames, activephasenames, &BDlines::kickedPhasesFunctionCallback, this, std::placeholders::_1, &BDlines::activePhasesFunctionCallback, this, std::placeholders::_1));
这和std ::占位符:: _ 1是一个可变argments。
的解决方案之前,看着这样的:
kicked_property = new FunctionProperty("kicked", &BDlines::kickedPhasesFunctionCallback, this, std::placeholders::_1);
activated_property = new FunctionProperty("activated", &BDlines::activePhasesFunctionCallback, this, std::placeholders::_1);
如何c + +知道哪些参数属于哪个模板参数?这如何以简单的方式实现?
我目前的解决方案是使用两个额外的功能,添加属性“激活”,然后属性“踢”,基本上像旧版本,但我只想使用一个单一的电话。
答
C++如何知道哪些参数属于哪个模板参数?
它没有。这就是为什么模板参数包只有在它们是最后一个参数时才能被引用的原因。
这怎么能以简单的方式实现?
如果每个组参数,只用于构造属性,可以只取属性的参数包:
model->addProperty(new PhaseSetControlProperty(kickedphasenames, activephasenames,
new StringListProperty (&BDlines::kickedPhasesFunctionCallback, this, std::placeholders::_1),
new StringListProperty (&BDlines::activePhasesFunctionCallback, this, std::placeholders::_1)));
的有还支持有产者其他种类和数量的额外好处。
答
不知道我是否完全理解了你的问题,但是你可以传递函子作为模板参数而不是分别传递函数和参数吗?所以,你的代码可能是这样的:
template<typename FuncKickedFunctor, typename FuncActivatedFunctor>
PhaseSetControlProperty(const std::vector<std::string> &kickedPhaseNames, const std::vector<std::string> &activatedPhaseNames, FuncKickedFunctor funcKickedFunctor, FuncActivatedFunctor funcActivatedFunctor): ControlProperty("PhaseSetControl")
{
getModel()->addProperty(new StringListProperty("kickedPhaseNames", kickedPhaseNames));
getModel()->addProperty(new StringListProperty("activePhaseNames", activatedPhaseNames));
getModel()->addProperty(new StringListProperty("activated", activatedPhaseNames, funcActivatedFunctor));
getModel()->addProperty(new StringListProperty("kicked", kickedPhaseNames, funcKickedFunctor));
}
答
你可以使用std::tuple<>
收集的参数 - 比如
template <typename... Args1, typename... Args2>
void foo(const tuple<Args1...>& t1, const tuple<Args2...>& t2) {
cout << tuple_size<tuple<Args1...>>::value << ' ' << tuple_size<tuple<Args2...>>::value << endl;
}
现在传播到构造元组...
请换行等等。您问题的重要部分不会隐藏在滚动条的后面。 –