如何声明用于名称空间中unordered_set的哈希函数? [英] How can I declare a hash function for use in an unordered_set within a namespace?

查看:127
本文介绍了如何声明用于名称空间中unordered_set的哈希函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为自定义类成功创建了哈希函数(和==覆盖),因此可以在unordered_set中使用它.但是,理想情况下,我想在要使用的类附近为我的类定义模板特化.这可以通过以下方法完成,效果很好:

I've successfully created a hash function (and == override) for a custom class so I can use it in an unordered_set. However, ideally I'd like to define the template specialization for my class near the class that it's to be used for. This can be done by the following, which works fine:

class MyClass {
public:
    MyClass() { _id = _nextId++; }
    const int id() const { return _id; }
private:
    int _id;
    static int _nextId;
};

int MyClass::_nextId = 0;

template<>
struct std::hash<MyClass> {
    std::size_t operator()(const MyClass& k) const {
        return k.id();
    }
};

但是,MyClass是在自定义名称空间中声明的.我以为使用全局范围解析运算符::,但这不起作用:

However, MyClass is declared in a custom namespace. I thought that using the global scope resolution operator ::, but that doesn't work:

namespace mine {
    // ...

    template<>
    struct ::std::hash<MyClass> {
        // ...
    };
}

因此,似乎我想在某个名称空间的括号内包含一些内容,以声明某些内容位于另一个名称空间中.写完最后一句话使我意识到这可能是不可能的,但是将散列函数放在要散列的类附近的想法似乎是个好主意.

So, it seems like I want to have something within the enclosing braces of a namespace declare something to be in another namespace. Writing that last sentence makes me realize that this is probably not possible, but the idea of having the hash function near the class it's hashing seems like a good idea.

这可能吗?最佳做法是什么?

Is this possible? What is the best practice for this?

推荐答案

您已经发现,如果要添加std::hash的特殊化,必须在std命名空间内完成.如果不希望这样做,另一种选择是将哈希函子保留在您的命名空间中,并将其作为模板参数传递给

As you've discovered, if you want to add a specialization for std::hash that must be done within the std namespace. If this is undesirable, another option is to keep the hash functor within your namespace and pass it as a template argument to unordered_set

namespace mine {

class MyClass { ... };

struct MyClass_hash {
  std::size_t operator()(const MyClass& k) const {
    return k.id();
  }
};

}

std::unordered_set<mine::MyClass, mine::MyClass_hash> my_set;

您还可以为unordered_set创建一个typedef,以节省一些打字输入.

You can also create a typedef for the unordered_set to save yourself some typing.

这篇关于如何声明用于名称空间中unordered_set的哈希函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆