【发布时间】:2016-03-31 15:00:10
【问题描述】:
我有一个相当简单的模板类,我将项目存储在一个向量中。但是,当我尝试擦除元素时出现以下错误:
C2678: binary '==': no operator found which takes a left-hand operand of type
'TestComponent' (or there is no acceptable conversion)
这是我正在使用的代码:
#pragma once
#include <vector>
template<class T>
class ComponentManager {
ComponentManager() {};
~ComponentManager() {};
T* newComponent() {
components.emplace_back(T());
return &components.back();
}
// This is the method I'm having trouble with
void destroyComponent(T* t) {
components.erase(std::remove(components.begin(), components.end(), *t), components.end());
}
private:
std::vector<T> components;
};
是的,我知道这会导致指针无效等等。不用去那里。
【问题讨论】:
-
TestComponent是否定义了operator ==? -
@NathanOliver 它没有。我想尽量不要它,因为泛型类型几乎可以是任何东西。我可能只是制定了删除错误。
-
与手头的问题无关,不必写
emplace_back(T()),直接写emplace_back()即可 -
@manabreak 为了删除某些内容,您需要检查它们是否相等。如果你想提供一种比较两个对象的方法,你需要使用
remove_if。 -
为什么使用原始指针而不是引用?