I'm implementing an ECS framework for my game engine and investigating ways to identify component types at runtime. This means I can dynamically group components of a similar type contiguously in memory. For example, I can have two separate arrays for Position
and Velocity
components that my systems can loop over.
I currently use typeid()
, but I came across an article that uses static const
variables to generate unique IDs for each type. The general idea can be summarized in the code snippet below:
#include <iostream>
struct Position { float x, y; };
struct Velocity { float dx, dy; };
template <typename T>
int test(int x) {
static const int y = x;
return y;
}
int main(int argc, char **argv) {
std::cout << test<Position>(1) << " ";
std::cout << test<Position>(2) << " ";
std::cout << test<Velocity>(3) << " ";
return 0;
}
This outputs 1 1 3
, but I would expect that since it's attempting to modify a constant (specifically at the second call), it would fail to compile. Why does this work?