我有以下回调系统
class ... {
...
std::vector<std::function<void()>> systemBringUps;
std::vector<std::function<void()>> systemTearDowns;
std::vector<std::function<void(EntityID_t)>> systemMains;
std::vector<std::function<bool(EntityID_t)>> systemChecks;
template <typename T>
void registerSystem() {
systemBringUps.push_back(T::systemBringUp);
systemTearDowns.push_back(T::systemTearDown);
systemMains.push_back(T::systemMain);
systemChecks.push_back(T::systemCheck);
T::onSystemRegister();
}
template <typename T>
void deregisterSystem() {
std::function<void()> bringUp = T::systemBringUp;
std::function<void()> tearDown = T::systemTearDown;
std::function<void(EntityID_t)> smain = T::systemMain;
std::function<bool(EntityID_t)> check = T::systemCheck;
std::remove(systemBringUps.begin(), systemBringUps.end(), bringUp);
std::remove(systemTearDowns.begin(), systemTearDowns.end(), tearDown);
std::remove(systemMains.begin(), systemMains.end(), smain);
std::remove(systemChecks.begin(), systemChecks.end(), check);
T::onSystemDeregister();
}
registerSystem
模板函数运行良好,但deregisterSystem
函数编译失败,显示以下错误信息:
...
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.5.0/../../../../include/c++/7.5.0/bits/predefined_ops.h:241:17: error: invalid operands to binary expression
('std::function<bool (unsigned short)>' and 'const std::function<bool (unsigned short)>')
{ return *__it == _M_value; }
~~~~~ ^ ~~~~~~~~
...
看起来像是std::remove
无法编译,因为我定义的deregisterSystem
中的std::function
是const
的,而我尝试从中删除的向量不是? 有没有办法从这些std :: function
中丢弃const
修饰符? 我尝试使用复制构造函数,如下所示:
template <typename T>
void deregisterSystem() {
std::function<void()> bringUp(T::systemBringUp);
std::function<void()> tearDown(T::systemTearDown);
std::function<void(EntityID_t)> smain(T::systemMain);
std::function<bool(EntityID_t)> check(T::systemCheck);
std::remove(systemBringUps.begin(), systemBringUps.end(), bringUp);
std::remove(systemTearDowns.begin(), systemTearDowns.end(), tearDown);
std::remove(systemMains.begin(), systemMains.end(), smain);
std::remove(systemChecks.begin(), systemChecks.end(), check);
T::onSystemDeregister();
}
但是这种方法同样会失败。