1

I have a set of classes that derive from the same base classes that roughly look like this:

class IClass
{
public:
    virtual int64_t getIdentifier() const = 0;
};

template<int64_t ID>
class Base : public IClass
{
public:
    static const int64_t s_identifier = ID;
    virtual int64_t getIdentifier() const { return s_identifier; }
};

I want to use the static s_identifier to identify a set of derived classes (I know there is the typeid operator but I would like to find another solution).

One derived class could for example look like this:

class Derived : public Base<0x630aea1e>
{
};

I'm searching for a way to get warned if there are two derived classes with the same identifier (to avoid copy&paste errors or simply because someone puts two times 0x12345678 as ID). I think it must be done at compile time but I currently cannot think of a way how to do this, maybe someone can help me.

bender
  • 613
  • 1
  • 8
  • 23
  • Not sure if there is a way in the language to do what you want. You could always do a unit test that makes sure all the ID's are unique. – NathanOliver Jan 16 '17 at 13:37
  • You need to know all the class types in advance. – Vittorio Romeo Jan 16 '17 at 13:38
  • 2
    question seems to be very similar to [this](http://stackoverflow.com/q/41639900/4324224) (not necessarily duplicate) – W.F. Jan 16 '17 at 13:39
  • 1
    You can't know this at compile time, because you can't know what types other translation units will instantiate. At best, you might be able to come up with scheme that generates a linker error. – François Andrieux Jan 16 '17 at 13:39
  • Note you can let the compiler generate ID's for all your classes, but also be sure to read the comments, as there are notoriously non-conformant compilers that mess up this trick: http://stackoverflow.com/a/7692147/256138. – rubenvb Jan 16 '17 at 13:56
  • I've once tried to find a solution to this exact problem. Couldn't with my approach because constexpr functions can't operate on a static data member / global variable. It could be done at runtime though – bolov Jan 16 '17 at 15:15

0 Answers0