I’m trying to create a global (singleton) class that can associate any type of object with an integer value. I was thinking of using a map<T*, int> variable, but was wondering if there was any other way to do it.
UPDATE: Here is a prototype of my class. Let me know what I’m doing wrong ! It compiles and work fine, but I’m not sure if it could be done in a better way. For instance, int addr = (int)&objectA; looks pretty ugly.
UPDATE 2: I’ve chosen to go the inheritance way as proposed by Potatoswatter. That will be much easier considering what I’m trying to achieve. Thanks everyone for the feedback !
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct PortPin {
int port;
int pin;
};
class Carte {
public:
void associate(int object_address, int port, int pins);
map<int, PortPin> map_;
};
void Carte::associate(int object_address, int port, int pins) {
PortPin values = {port, pins};
map_[object_address] = values;
}
class A {
public:
A() {}
};
class B {
public:
B() {}
};
void main() {
Carte carte;
A objectA;
B objectB;
int addr = (int)&objectA;
carte.associate(addr, 2, 7);
cout << "Port: " << carte.map_[addr].port
<< " Pin: " << carte.map_[addr].pin;
}
You should use a base class.
The kind of pointer arithmetic you’re trying to do isn’t treading water, it’s treading fiery acid.
It’s not really that important to be able to associate any object. Were you going to associate your singleton with a PortPin? Always derive every class from an appropriate base to acquire needed services.
If you’re concerned about the memory (a dozen or two bytes at most) taken by the PortPin base, you can create an empty base class to give you a
T*type with which to key yourmap. However, consider that eachmapentry takes three pointers plus the data, hence being at least twice as big as the PortPin struct itself. And it will leak unless you’re careful, and that will cause mysterious bugs when addresses are reused. (This problem would be all but impossible to eliminate if you really can’t constrain the key classes.) Finally, the map is much slower and more tedious than just accessing a field.