galinette
galinette

Reputation: 9292

Statically assign IDs in c++

It's rather easy to create a unique identifier class, which ensures every instance will automatically be attributed a unique integer upon construction:

class UniqueIdentifier
{
    UniqueIdentifier() { static int NextFreeId = 0; Id = NextFreeId++; }
    int Id;
};

But is this possible statically? What I would like to achieve is:

class Base
{
    static constexpr const UniqueIdentifier Foo1
    static constexpr const UniqueIdentifier Foo2;
    static constexpr const UniqueIdentifier Foo3;
}

class Derived : public Base
{
    static constexpr const UniqueIdentifier Bar1
    static constexpr const UniqueIdentifier Bar2;
    static constexpr const UniqueIdentifier Bar3;
}

And have each member being a unique compile-time integer. Having the numbering sequential is a plus, and 0-based for the base class would be awesome. But those are not a strict requirement. This sounds similar in concept to extending enums

Upvotes: 0

Views: 58

Answers (0)

Related Questions