代码之家  ›  专栏  ›  技术社区  ›  bird12358

模板函子的哈希表

  •  0
  • bird12358  · 技术社区  · 8 年前

    我想创建一个hastable to member模板函子,我解释道。

    #include <iostream>    
    #include <unordered_map>
    
    using namespace std;
    class MyFirstClass
    {
        int i_;
    
    public:
        MyFirstClass(): i_(0) {}
    
        void setI(int i) { i_ = i; }
        int getI() { return i_; }
    };
    
    class MySecondClass
    {
        bool b_;
    
    public:
    
        MySecondClass(): b_(0) {}
    
        void setB(bool b) { b_ = b; }
        bool getB() { return b_; }
    };
    
    template<class X, void (X::*p)()>
    class MyFunctor
    {
        X& _x;
    public:
        MyFunctor(X& x) : _x( x ) {}
        void operator()() const { (_x.*p)(); }
    };
    
    int main(int argc, char *argv[])
    {
        unordered_map<string,MyFunctor> myHashTable;
    
        MyFirstClass first;
        MyFirstClass second;
    
        myHashTable["int"] = first::setI;
        myHashTable["bool"] = second::setB;
    
        //
        string key = "bool";
        int value = 1;
    
        myHashTable[key](value);
    
        return 0;
    }
    

    前面的代码暂时不起作用,我被卡住了。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Caleth    8 年前

    目前,您的代码存在一些问题。

    首先,从你的例子来看 unordered_map<string,MyFunctor> 没有命名类型,因为 MyFunctor operator() ,然后让MyFunctor从中继承。

    MyFirstClass::setI MySecondClass::setB 两者都接受一个参数。

    构造函数以及方法指针模板参数。

    class MyFunctorBase {
        virtual void operator()(void * i) const = 0;
    }
    
    template<class T, class X, void (X::*p)(T)>
    class MyFunctor : public MyFunctorBase 
    {
        X& _x;
    public:
        MyFunctor(X& x) : _x( x ) {}
        void operator()(void * i) const override { (_x.*p)(*static_cast<T*>(i)); }
    };
    
    int main(int argc, char *argv[])
    {
        unordered_map<string,shared_ptr<MyFunctorBase>> myHashTable;
    
        MyFirstClass first;
        MyFirstClass second;
    
        myHashTable["int"] = make_shared<MyFunctor<int, MyFirstClass, &MyFirstClass::setI>>(first);
        myHashTable["bool"] = make_shared<MyFunctor<bool, MySecondClass, &MySecondClass::setB>>(second);
    
    
        //
        string key = "bool";
        bool value = true;
    
        (*myHashTable[key])(static_cast<void *>(&value));
    
        return 0;
    }
    

    或者更容易地使用现有的 std::function ,对你来说就是这样

    int main(int argc, char *argv[])
    {
        unordered_map<string,function<void(void *)>> myHashTable;
    
        MyFirstClass first;
        MyFirstClass second;
    
        myHashTable["int"] = [first](void * i) { first.setI(*static_cast<int *>(i)); };
        myHashTable["bool"] = [second](void * i) { second.setB(*static_cast<bool *>(i)); };
    
    
        //
        string key = "bool";
        bool value = true;
    
        myHashTable[key](static_cast<void *>(&value));
    
        return 0;
    }
    
    推荐文章