Cocoa Objective-C:使用c++对象作为NSDictionary键
Cocoa Objective-C: use c++ objects as NSDictionary keys?
我有一个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
这是一个相当大的数字,这使得相对较少的物体不太可能发生碰撞。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- Cocoa Objective-C:使用c++对象作为NSDictionary键