OiO.lk Blog templates C++ template: access members from source template struct
templates

C++ template: access members from source template struct


I want to create following class template:

  • Holds a list of objects of different classes, at compile time.
  • Being alled to do some computation on all members from a function.
  • Has a member to access each object of the list individually.
  • List and members can be created at compilation, no need for dinamic lists.
  • User interface must be simple, since it will be used many times and by different programmers on the teams, with little c++ experience.
  • Use C++14 standard, gcc compiler.

Example of user code. This is what I want to keep as simple as possible:

//list of sensors with a member for each sensor
typedef struct {
    cOneSensor_f A4_temp1 = cOneSensor_f ("A4t1", 0x1234 /*, x, y, ... and some more configuration data*/);
    cOneSensor_i B4_speed = cOneSensor_i ("B4s0", 0x2001 /*, x, y, ... and some more configuration data*/);
}Sensor_list_4_s;

//put the list inside a class template to be able to control all of them as a whole,
//but also access each sensor individually
cSensorsList<Sensor_list_4_s> Sensor_list_4( 4 );

//get sensor values
void do_sensors_stuff()
{
    //all sensors as a whole
    Sensor_list_4.update();

    //access each sensor individually
    float A4t1 = Sensor_list_4.A4_temp1();
    int   B4s0 = Sensor_list_4.B4_speed();
}

Behind the scene It can be as complicated as needed. It could be somehting like this:

  • A base class for objects
  • Some derived classes for different objects variations (I can manage all derived classes from base)
  • Template class to hold the list of objects.
class cOneSensor {}
class cOneSensor_f: class cOneSensor {}
class cOneSensor_i: class cOneSensor {}

template <typename T>
class cSensorsList: public T
{
private:
    int bus_code;
    cOneSensor *sensors_array;
    int nSensors;

public:
    cSensorsList(int bus_code):bus_code(bus_code)
    {
        //---  here is what I don't know how to do: get sensor list from typename T
        nSensors = 0; //getSensorListSize_from_T(/* T */);
        sensors_array = 0;//getSensorListPointer_from_T<T>(/* T */);
        // ---
    }
    void update(void) {
        for (int i=0; i<nSensors; i++)
            sensors_array[i].update();
    }
};

With this code I get:

  • ✅ Members on cSensorsList to access each object individually.
  • ✅ Symple to user perspective.
  • ✅ All objects in a class.

But I don’t know how to:

  • Within the class cSensorsList, get the list of members of template struct, to loop through all objects in the list to so some actions: the getSensorListPointer_from_T() function.



You need to sign in to view this answers

Exit mobile version