Noob at C ++: how to make an associative array of an object => value?

I am trying to create a global (singleton) class that can bind any type of object with an integer value. I was thinking about using a variable map<T*, int>, but I was wondering if there is another way to do this.

UPDATE: Here is a prototype of my class. Let me know what I'm doing wrong! It compiles and works fine, but I'm not sure if this could be done better. For example, int addr = (int)&objectA;it looks pretty ugly.

UPDATE 2: I chose the inheritance path suggested by Potatoswatter. It will be much easier given what I'm trying to achieve. Thank you all for your 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;
}
+3
source share
3 answers

.

struct PortPin {
    int port;
    int pin;
    bool is_valid;

    PortPin() { is_valid = false; }

    void associate( int in_port, int in_pin ) {
        port = in_port;
        pin = in_pin;
        is_valid = true;
    }
};

class A : public PortPin {
    public:
    A() {}
};

class B : public PortPin {
    public:
    B() {}
};


A blah;
A.associate(2,7);

, , - , .

. PortPin? .

( ), PortPin, , T*, map. , map , , , PortPin. , , . ( , .) , , .

+2

, (unsigned long) (intptr_t , C99, ++).

, . , , , typeid (T), ( ).

+1

, " ", " ", , , . , , , , , . , , , - (, ), , .

, Potatoswatter, . , , , - , ; , . , , , !

, , ( Potatoswatter ), ints; , , . , , , , - , T * void, map<void*, PortPin>.

It will also be difficult that the object and its first component (and that component of the first component, etc.) will have the same pointer and, therefore, will all be associated with the same search value on your map. If you are interested, you can build a structure containing both a pointer and an identifier of the type (a std::type_infocontaining the typeid()object, or intfor your own sizeof()if you compile without RTTI on and therefore typeid()not available) and use this as a tag for the map.

+1
source

Source: https://habr.com/ru/post/1734977/


All Articles