c++ - 如何处理 C++ HashMap get(key) 函数中的未命中?

标签 c++ pointers c++11 reference hashmap

我在 C++ 中实现了一个 hashmap,以便了解更多关于关联映射的一般信息,除了一个症结点外,一切都很好——我希望程序员能够创建具有任意参数化的映射(例如 [使用 std::string示例] HashMap<string,string*>HashMap<string,string>HashMap<string*,string> 等都是合法的)。

问题在于,在 HashMap::get(int key_data) 函数中,如果我支持将对象作为映射值,则返回的映射值(其中给定键与任何映射值都不匹配)不能简单地为 NULL。我可以让 get(...) 函数始终返回一个指向参数化映射值类型的指针,但如果该类型已经是一个指针,我就不能使用一元 & 运算符,如果它是一个对象,我必须使用 & 运算符。我肯定不想用RTTI,所以问题如下:

我如何允许从我的 HashMap::get() 函数返回对象和指向对象的指针类型,这也是允许未命中所必需的?

请记住,我使用的是 gcc 4.7 并启用了 C++11,因此所有 C++11 功能和注意事项均适用。到目前为止,下面是我的 HashMap::get() 函数,它使用“始终返回指向任何 value_data 恰好是的指针”范例:

template <class key_data,class value_data> value_data*  
HashMap<key_data,value_data>::get(key_data dk) {

    int key = keyGen(dk);

    int hash_val = HashFunc(key);
    HashNode* entry = _table[hash_val];

    while (entry != 0) {
        if (entry->getCurrentKey() == key) {

            //value_data val = entry->getCurrentValue(); //this temporary will be 
            //gone from the stack quickly and therefore the returned pointer to a 
            //pointer (if value_data is a pointer) will segfault

            return &(entry->getCurrentValue()); //this should be legal and yield 
            //a pointer to a pointer (iff value_data was a pointer), but instead 
            //I get a compiler error claiming 
            //operator & requires an lvalue operand...
        }

        entry = entry->next();

    }

    printf("Your get of int key %i resulted in no hits."
           "The returned pointer to Value is NULL!\n",key);


    return NULL;
}

如评论所述,return &(entry->getCurrentValue()); 行抛出编译器错误,指出运算符 & 需要左值操作数。我可以通过在堆栈上放置一个 value_data 临时值来消除该错误,但是当我实际尝试使用它时这将导致段错误,因为返回的指针几乎立即无效。简单地使用引用来抽象语法问题也不起作用,因为在那种情况下无法通过返回 NULL 实现未命中(ISO 要求引用,与原始指针不同,指向有效的左值)。

如果有人有关于处理可能“无效”的返回引用的建议(比如可以查询有效性的虚拟对象,其他所有内容都继承自该对象),我也愿意接受。

最佳答案

解决这个问题的一种可能方法是部分模板特化。有关如何为指针执行此操作的示例,请参阅 this other question .

基本上(从那里的答案复制),你需要

template <class I>
class GList<I*>
{
    ...
};

为任何指针类型提供专门版本的列表。

关于c++ - 如何处理 C++ HashMap get(key) 函数中的未命中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19367642/

相关文章:

c++ - C++ 中的二叉树

c++ - 将缓冲区/指针设置为空

c - 该堆栈程序的内存分配不均匀

c++ - 如何强制编译器为手动切换生成等效代码?

c++ - 将 C++ 中的列表对象移动到另一个对象

c++ - Visual Studio 2015 Go To Definition 转到错误的类

c++ - 如何在 linux 上编译 libserial?

c++ - 什么是 "abstractions"?

c++ - 添加具有 size_t 类型值的指针

c++ - 如何在成员函数上使用 std::async?