有没有一种基于类型创建唯一ID的好的模式? [英] Is There a Good Pattern for Creating a Unique Id based on a Type?

查看:63
本文介绍了有没有一种基于类型创建唯一ID的好的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板,可以为每个实例创建一个唯一的标识符.这是模板的简化版本:

I have a template that creates a unique identifier for each type it is instanced. Here's a streamlined version of the template:

template <typename T>
class arType {
  static const arType Id; // this will be unique for every instantiation of arType<>.
}

// Address of Id is used for identification.
#define PA_TYPE_TAG(T) (&arType<T >::Id)

当您具有完全由静态库组成的可执行文件时,此方法有效.不幸的是,我们正在转向由dll组成的可执行文件.每个dll可能都有其自己的类型ID副本.

This works when you have an executable made purely of static libraries. Unfortunately we're moving to an executable made up of dlls. Each dlls could potentially have its own copy of Id for a type.

一个明显的解决方案是显式实例化arType的所有实例.不幸的是,这很麻烦,我想问问是否有人可以提出更好的解决方案?

One obvious solution is to explicitly instantiate all instances of arType. Unfortunately this is cumbersome, and I'd like to ask if anyone can propose a better solution?

推荐答案

从每个对象上的函数返回一个std :: type_info对象,并对结果使用==运算符.您可以使用before()函数对它们进行排序,该函数返回排序顺序.

Return a std::type_info object from a function on each object and use operator == on the result. You can sort them by using the before() function which returns the collation order.

它是专门为您想要做的而设计的.您可以使用运算符<将其包装为不透明的"id"类型.如果您想隐藏它的工作原理.

It's specifically designed to do what you want. You could wrap it in an opaque "id" type with an operator< if you wanted to hide how it works underneath.

http://www.cplusplus.com/reference/std/typeinfo/type_info/

这篇关于有没有一种基于类型创建唯一ID的好的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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