Cocoa Objective-C:使用c++对象作为NSDictionary键

Cocoa Objective-C: use c++ objects as NSDictionary keys?

本文关键字:NSDictionary 对象 c++ Objective-C 使用 Cocoa      更新时间:2023-10-16

我有一个c++框架,我正在使用我的Objective-C (Cocoa)代码。我目前实现包装类来传递我的c++对象周围的obj-C代码。

c++对象被存储为一个层次结构,并且,我最近意识到我需要在obj-C对象和c++对象之间有一个一对一的对应关系,因为我使用这些作为NSOutlineView项,a)需要是obj-C对象,b)需要是精确的(即,我需要给相同的obj-C对象每次对应的c++对象)。

我有点纠结于最好(即最简单)的方法。理想情况下我会有一个NSDictionary,我输入c++对象作为键,然后得到相应的obj-c对象。是否有任何方法将c++对象转换为唯一的键,以便我可以以这种方式使用NSDictionary ?或者是否有其他实用的方法来编写函数来实现类似的目的?

是的,当然可以将任何类对象转换为哈希值。下面的代码演示了如何对用户定义的类型std::hash进行专门化:

#include <iostream>
#include <functional>
#include <string>
struct S
{
    std::string first_name;
    std::string last_name;
};
namespace std
{
    template<>
    struct hash<S>
    {
        typedef S argument_type;
        typedef std::size_t result_type;
        result_type operator()(argument_type const& s) const
        {
            result_type const h1 ( std::hash<std::string>()(s.first_name) );
            result_type const h2 ( std::hash<std::string>()(s.last_name) );
            return h1 ^ (h2 << 1);
        }
    };
}
int main()
{
    S s;
    s.first_name = "Bender";
    s.last_name =  "Rodriguez";
    std::hash<S> hash_fn;
    std::cout << "hash(s) = " << hash_fn(s) << "n";
}

和一个示例输出:

hash(s) = 32902390710

这是一个相当大的数字,这使得相对较少的物体不太可能发生碰撞。