簡體   English   中英

使用類成員變量來保存內部結構定義中的函數,這些內部函數將用作unordered_map對象的模板參數

[英]Using class member variables that hold functions in definition of inner structures that will be used as template arguments of an unordered_map object

我正在實現一個使用unordered_map的對象。 對象是通用的,因此模板無處不在。 特別是, operator==operator()被包裝到unordered_map使用的結構中,以分別檢查鍵是否相等並生成鍵的哈希值。 我希望用戶編寫自己的函數來實現上述兩個運算符,並將這些方法作為輸入傳遞給類對象。 然后,這些結構將使用這些對象。 我在使用示波器時遇到了麻煩,似乎無法弄清楚該怎么做。 這是我的代碼:

#include <unordered_map>
#include <iostream>
#include <string>
#include <functional>

template <typename O>
class aClass
{
public:
    aClass( bool        (usrIsEq)(O, O) , 
            std::size_t (usrHashFtn)(O) ) 
    {
        this->usrIsEq    = usrIsEq;
        this->usrHashFtn = usrHashFtn;
    }

    void add(O k, std::string v)
    {
        iTable[ {k} ] = v;
    }

    std::string get(O k)
    {
        return iTable[ {k} ];
    }


private:
    bool        (*usrIsEq)(O, O);
    std::size_t (*usrHashFtn)(O);

    struct Key
    {
        O obj;

        bool operator==(const Key &other)    const
        {
            std::cout <<  "obj " <<   obj << std::endl;
            return usrIsEq(obj, other.obj);
        }
    };

    struct KeyHasher
    {
        std::size_t operator()(const Key &k) const
        {
            return usrHashFtn(k);
        }
    };  
    std::unordered_map<Key, std::string, KeyHasher> iTable;

};

bool isEqInts(int a, int b)
{
    return a == b;
}

std::size_t intHashFtn(int x)
{
    std::hash<int> hf;
    return  hf(x);
}

int main()
{
    aClass<int> x(isEqInts, intHashFtn);
    x.add( 1, std::string("hello") );
}

我不完全確定如何實現structKeyKeyHasher以便它們使用類中包含的功能。 我真正關心的唯一事情是,這些函數是作為類構造函數的輸入提供的。 其他一切都可以報廢。

使您usrIsEq的主要問題是Key不了解usrIsEqKeyHasher不了解usrHashFtn 您需要將指向aClass對象的指針或引用aClass給這些類。

這是一個建議:

struct Key
{
    O obj;
    aClass* ac;

    bool operator==(const Key &other)    const
    {
        std::cout <<  "obj " <<   obj << std::endl;
        return ac->usrIsEq(obj, other.obj);
    }
};

struct KeyHasher
{
    std::size_t operator()(const Key &k) const
    {
        return k.ac->usrHashFtn(k.obj);
    }
};  

並更新您使用Key訪問表的位置:

void add(O k, std::string v)
{
    iTable[{k, this}] = v;
}

std::string get(O k)
{
    return iTable[{k, this}];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM