1

First let me apologize if the question sounds vague. Few years ago I saw a syntax which I can't recall. It allows me to create a pointer to a struct member.

What I'm trying to achieve is to create a member in my DoComplexCalculation class which points to a specific member in SensorData struct. To allow me to create many instances of the class where each instance work on different member of the struct (selected in the Init function).

The class

class DoComplexCalculation

    {
    public:
      void Init(std::string& which_member_to_work_on)
      {
         if (which_member_to_work_on == "Temperature")
            // initialize pointer to a Temperature struct member with, how ? 
         else if (which_member_to_work_on == "Humidity")
            // initialize pointer to a Humidity struct member with, how ?
      }
      void CalculateNow(const SensorData& sensorData)
      {
         int membertoworkon = // some syntax to select the member by the initialized pointer 
      }
     // Pointer to struct member, what is the syntax ?
    }

A struct with many integer members:

struct SensorData
{
  int Temperature;
  int Humidity;
  .
  .
  .
}
OopsUser
  • 4,642
  • 7
  • 46
  • 71
  • 1
    Does this answer your question? [Pointer to class data member "::\*"](https://stackoverflow.com/questions/670734/pointer-to-class-data-member) – UnholySheep Jan 02 '20 at 11:50
  • Doing something similar [here](https://stackoverflow.com/questions/59130612/sorting-function-for-a-vector-of-objects-based-on-different-fields/59130875#59130875) (Sorry for tooting my own horn). – n314159 Jan 02 '20 at 11:56
  • 1
    This is all round bad design. First off, using strings to encode logic is an instance of [stringly typed code](https://wiki.c2.com/?StringlyTyped), which is bad because it subverts the type system. Secondly, don’t have `Init` functions in your classes. Instead, use constructors — and initialise the object *fully*, never partially. – Konrad Rudolph Jan 02 '20 at 12:04

1 Answers1

2

You can use pointer on class member:

class DoComplexCalculation
{
    int SensorData::*memberPtr = nullptr;
public:
    void Init(const std::string& which_member_to_work_on)
    {
        if (which_member_to_work_on == "Temperature")
            memberPtr = &SensorData::Temperature;
        else if (which_member_to_work_on == "Humidity")
            memberPtr = &SensorData::Humidity;
         // ...
    }

    void CalculateNow(const SensorData& sensorData)
    {
         if (memberPtr == nullptr) { return; }         
         int membertoworkon = sensorData.*memberPtr;
         // ...
    }

};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • If this list gets really long, and you don't mind the dynamic allocation, you may want to consider migrating your data into a map. Or, if static allocation is important, have all your `int`s in an array, and make an enum which "names" the indexes of the array. – Lightness Races in Orbit Jan 02 '20 at 18:31