如何在虚拟类方法中使用std :: vector :: remove()?

Mat*_*ias 0 c++ vector c++11

我有以下课程:

template <class T>
class BeliefSet : public Belief<T>
{
private:
    std::vector<T> m_Facts;

public:
    void RemoveFact(const T Fact)
    {
        m_Facts.remove(Fact);
    }
};
Run Code Online (Sandbox Code Playgroud)

这很好用.但是,我想从中派生另一个类BeliefSet并覆盖此方法RemoveFact(),因此我将上面显示的代码更改为以下内容:

/* Rest of this class has not been changed. */

virtual void RemoveFact(const T Fact)
{
    m_Facts.remove(Fact);
}
Run Code Online (Sandbox Code Playgroud)

现在,一旦我编译,我得到这个错误:

error C2039: 'remove': is not a member of 'std::vector<std::string,std::allocator<_Ty>>'
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么想法?

Bar*_*rry 6

这很好用.

不,它没有.std::vector没有会员功能remove().但是,不急切地实例化类模板成员函数.你可能根本就没有调用过RemoveFact(),所以你永远不会遇到这个问题.这个"懒惰"实例化非常重要 - 它允许您编写和使用具有条件有效运算符的类模板,而无需编写SFINAE垃圾的负载(例如,我可以使用std::map非默认构造值类型,我只是不能使用operator[]) .

当你创建函数时virtual,就像你继承它一样,很可能你的编译器试图在那时实例化函数(未指定实现是否这样做 - 你的显然是这样做的).由于此函数格式错误,因此通过virtual函数实例化而不是正常的函数实例化来获取错误.

无论哪种方式,功能都被打破,你想要:

void RemoveFact(const T& Fact)
{
    m_Facts.erase(
        std::remove(m_Facts.begin(), m_Facts.end(), Fact),
        m_Facts.end());
}
Run Code Online (Sandbox Code Playgroud)