【问题标题】:Lookup for element in custom generic container (object transformation with lambdas) C++在自定义通用容器中查找元素(使用 lambda 进行对象转换)C++
【发布时间】: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


    【解决方案1】:

    传递给 lambda 的参数类型与存在的函数指针的参数类型不匹配。以下代码有效:

    typedef Vehicle* pVehicle;
    manager.exists(
                     lookFor, 
                     [](const pVehicle & a) -> std::string { return a->licensePlate;}
                  );
    

    区别在于指向指针的 const ref(函数指针需要)和指向 const 对象的指针的引用(在 lambda 中声明)

    【讨论】:

    • 感谢您的回复。但它也不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多