c++ - 安全且跨越库边界的唯一类类型 ID

标签 c++ class templates unique

感谢任何帮助,因为 C++ 不是我的主要语言。

我有一个在多个库中派生的模板类。我试图找出一种方法来为每个派生类唯一地分配一个 id int。不过,我需要能够通过静态方法来做到这一点,即。


template < class DERIVED >
class Foo
{
public:
    static int s_id()
    {
        // return id unique for DERIVED
    }
    // ...
};
谢谢!

最佳答案

这可以用很少的代码完成:

template < class DERIVED >
class Foo
{
public:
    static int s_id()
    {
        return reinterpret_cast<int>(&s_id);
    }
};

关于c++ - 安全且跨越库边界的唯一类类型 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/922442/

相关文章:

c++ - 如何简化复杂的 API 访问 (v8)

python - 将行视为外部定义类的实例吗?

c++ - 在g++中收到的预期主表达式

c++ - 模板特化编译器错误

c++ - 如何在 C++ 中为 GLSL 制作一维 lut

c++ - Qt 4.8 : connection behavior between two signals and one slot from different threads

c++ - 如何运行 C++ 代码以在 Raspberry Pi 上使用 Apache Webserver 与 GPIO 交互?

php - 具有特定类的 mysql_fetch_object

python - 如何从 Python 中用户创建的异常类的开头删除 "__main__."

c++ - 模板基类类型定义和函数的更好 C++ 语法?