我对 Qt 非常熟悉,我知道我们不能有类似的语法,因为我们这里没有 MOC 部分。但是,我正在尝试进行信号创建管理,以在我的类中简化信号声明及其连接。
这就是我现在正在做的事情
class Foo
{
công cộng:
void connectMove(boost::signal::slot_type slot)
void connectRotate(boost::signal::slot_type slot)
riêng tư:
boost::signal m_signalMove;
boost::signal m_signalRotate;
};
这基本上就是我想做的(大写 = 缺失部分)
class SignalManager
{
công cộng:
typedef boost::unrodered_map MapSignal;
công cộng:
template
bool connect(const std::string& strSignalName, boost::signal::slot_type slot)
{
// simplyfied... :
(*m_mapSignal.find(strSignalName))->connect(slot);
}
template
bool disconnect(const std::string& strSignalName, boost::signal::slot_type slot)
{
// simplyfied... :
(*m_mapSignal.find(strSignalName))->disconnect(slot);
}
được bảo vệ:
bool call(const std::string& strSignalName, SIGNAL_ARGS)
{
(*m_mapSignal.find(strSignalName))(SIGNAL_ARGS);
}
template
void delareSignal(const std::string& strSignalName)
{
m_mapSignals.insert(MapSignal::value_type(strSignalName, new boost::signal()));
}
void destroySignal(const std::string& strSignalName)
{
// simplyfied... :
auto it = m_mapSignal.find(strSignalName);
delete *it;
m_mapSignal.erase(it);
}
riêng tư:
MapSignal m_mapSignals;
};
class Foo : public SignalManager
{
công cộng:
Foo(void)
{
this->declareSignal("Move");
this->declareSignal("Rotate");
}
};
class Other : public boost::signals::trackable
{
công cộng:
Other(Foo *p)
{
p->connect("Move", &Other::onMove);
p->connect("Rotate", &Other::onRotate);
}
void onMove(int i)
{
/* ... */
}
void onRotate(double d)
{
/* ... */
}
};
我想我可以用 boost::functions_traits<> 解决“SIGNAL_ARGS”部分,但我不知道如何绕过抽象信号类型。
1/我想要的有可能吗?
2/这是一个好方法吗? (我知道由于 unordered_map.find,我会有一些开销,特别是当我使用 this->call("signalname", ...) 时,但我认为它不应该太重要)
3/如果这不可能或不是一个好方法,您还有其他建议吗?
我通过包装 boost::signals
解决了我的问题并且有一个 boost::shared_ptr
而不是我的 GENERIC_SIGNAL
.
参数问题也使用 boost::function_traits::arg_type
解决了.
我不知道这是否是最好的方法,但它工作正常,而且用户在继承此 SignalManager
的类中声明信号更简单。 .
Tôi là một lập trình viên xuất sắc, rất giỏi!