我正在构建一个通用类,它将管理任何类型的指针。
这是我的课:
GenericManager.h
template <class T> class GenericManager {
public:
void add(T element) const;
//!!!!!!!!!!!!!!!!!!!!!!
template <class R>
bool exists(const R& element, R(*fn)(const T& a)) const;
private:
List<T>* list = new ArrayList<T>(); //own implementation, has add, [], remove
}
存在方法实现
bool GenericManager<T>::exists(const R& elem, R(*fn)(const T& a) {
for(int i = 0; i < list->size(); i++) {
T e = (*list)[i];
if(fn(e) == elem) return true;
}
return false;
}
我希望 exist 方法检查列表是否包含具有特定属性的对象。将对象 T 转换为 R 并与来自参数的对象进行比较。
示例:
struct Vehicle {
string licensePlate;
}
string lookFor("ABCD");
GenericManager<Vehicle*> manager;
Vehicle *v = new Vehicle();
v->licensePlate = lookFor;
manager.add(v);
//check if manager managers vehicle with 'lookFor' license plate
manager.exists(
lookFor,
[](const Vehicle*& a) -> std::string { return a->licensePlate;}
);
但它没有编译:
no instance of function template "GenericManager<T>::exists [with T=Vehicle *]" matches the argument list
argument types are: (std::string, lambda []std::string (const Vehicle*& c)->std::string)
object type is: GenericManager<Vehicle *>
最佳答案
传递给您的 lambda 的参数类型与存在的函数指针的参数类型不匹配。以下代码有效:
typedef Vehicle* pVehicle;
manager.exists(
lookFor,
[](const pVehicle & a) -> std::string { return a->licensePlate;}
);
区别在于指针的 const 引用(函数指针需要)和指向 const 对象的指针的引用(在 lambda 中声明)
关于c++ - 在自定义通用容器中查找元素(使用 lambda 进行对象转换)C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49212996/