【发布时间】:2018-08-19 03:51:27
【问题描述】:
我正在构建一个通用类,它将管理任何类型的指针。
这是我的课:
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 *>
【问题讨论】:
标签: c++ generics lambda functional-programming