Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check integer constants have different values at compilation time

My question is the following. I have a large number of static const integers that work as Identifiers. For this reason I would like to know if it is possible to check at compilation time if there is more than one constant with the same value (some kind of static assert...).

I do not want to use an enum as these constants are defined in different modules and I don't want to have like a very long enum with all of them (and some of them are not related to each other).

Here you have a basic example:

// module: foo.h
const uint32_t ELEMENT_TYPE_FOO_X = 46;
const uint32_t ELEMENT_TYPE_FOO_Y = 51;
...

// module: boo.h
const uint32_t ELEMENT_TYPE_BOO_C = 21;
const uint32_t ELEMENT_TYPE_BOO_D = 51;

error: ELEMENT_TYPE_FOO_Y and ELEMENT_TYPE_BOO_D have the same value.

I'm not an expert at all and the only thing that comes to my mind to detect this error is template specialization.

template<uint32_t N>
struct element_traits {
};

template<ELEMENT_TYPE_FOO_X> {
    enum { value = ELEMENT_TYPE_FOO };
};

But it seems to be a complex solution. I don't know if there is a more elegant/better solution. I haven't found anything so far.

Thanks in advance.

like image 675
user1192525 Avatar asked Jul 16 '26 06:07

user1192525


1 Answers

You could certainly do this using macros:

#define UNIQUE_CONSTANT(variable, value) \
  const uint32_t variable = value; \
  bool constant_val_##value = value;

Then you will get a multiple definition error if the same value is used twice.

(Technically, this will detect the error at link time, not compile time.)

like image 137
Keith Randall Avatar answered Jul 17 '26 20:07

Keith Randall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!