模板中的 C++ 函数指针

标签 c++ templates function-pointers

我已分配到以下模板:

#include <map>

template <typename T> 
class Catalog { 
    struct Item { 
        //..
    };
    std::map<int, Item*> items;
public: 
    Catalog(void); 
    Catalog(const Catalog&); 
    ~Catalog(void); 
    bool IsEmpty(void) const;
    int Size() const; 
    void Add(T*); 
    T* Remove(T*); 
    T* Find(T*); 
    typedef void (T::*pFunc) (const T&); 
    void Inspection(pFunc) const; 
};

接下来是一个抽象的Product类和三个子类:

class Product {
protected:
    unsigned int _id;
    string _name;
public:
    Product(const int& id, const string& name) : _id(id), _name(name) {};
    virtual void Action(const Product& p) = 0;
    virtual int hashCode() {
        return _id*100;
    };
    unsigned int getId(void) const {return _id;};
    string getName(void) const {return _name;};    
};

class ProductA : public Product {
public:
    ProductA(const int& id, const string& name) : Product(id, name) {};
    virtual void Action(const Product& p) {
        cout << "ahoj" << endl;
    };
};

最后,处理 Catalog 实例的 ProductsCatalog 类:

class ProductsCatalog {
    Catalog<Product> catalog;
public: 
    //..
    void CatalogInspection(void) const {
        catalog.Inspection(&Product::Action);
    }
};

我遇到的问题是检查方法:

template <typename T> void Catalog<T>::Inspection(pFunc p) const {  
    for (std::map<int, Item*>::const_iterator it=items.begin(); it!=items.end(); ++it)  {
        it->second->Product->*p(*(it->second->Product));
    }
};

我收到以下错误:

error C2064: term does not evaluate to a function taking 1 arguments

我已经尝试了所有我能想到的方法,但没有成功。以下内容按预期工作,但显然不够抽象:

it->second->Product->Action(*it->second->Product);

最佳答案

你试过了吗 (it->second->Product->*p)(*(it->second->Product)); 调用方法? 跟帖 Calling C++ class methods via a function pointer似乎是相关的。

关于模板中的 C++ 函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582431/

相关文章:

Django 模板用户请求

c++ - 在构造函数上启用_if

c++ - 在没有 typedef 的情况下在 C++ 中返回函数指针时出错

c++ - C++中的算术溢出添加了2个SWORD

c++ - 允许我更改 QwtPlot 颜色背景的方法

C++11 从初始化列表到数组参数的隐式转换

c++ - 通过函数指针计算的 goto/jump 与 fastcall 哪个成本更高?

c - 回调与用于事件处理的条件函数调用有何不同和优势?

c++ - C++ 类中的类

c++ - 动态规划 - 事件选择