-1

I'm trying to create a map of strings to functions. When it's a simple function, I've seen how to do this like so:

typedef int (*GetIntFunction)(void);

int get_temp()
{
  return 42;
}

map<string, GetIntFunction> get_integer_map { { "temp", &get_temp } };

auto iter = get_integer_map.find("temp");
int val = (*iter->second()();

However, I'd like my function pointer to be to a function of a specific object. And, I know which object I need at map creation. Something like this:

class TemperatureModel
{
public:
  int GetTemp();
}

TemperatureModel *tempModel = new TemperatureModel();

map<string, GetIntFunction> get_integer_map { { "temp", &(tempModel->GetTemp} };

If you'd like to know why I'm doing this, I'm trying to read a list of parameters from an input file, get their values from the correct model, and then output their values to an output file. I will also need to set values at runtime using a similar map.

bsh152s
  • 3,178
  • 6
  • 51
  • 77
  • Reopened. The purported duplicate was just a map of PMFs. This question is about binding an object and a function. – Pete Becker Oct 24 '18 at 21:44
  • 2
    `GetTemp` is not static is a member function. `typeof(GetTemp) = int (*TemperatureModel::)(void)` not `int (*)(void)`. Use std::function – KamilCuk Oct 24 '18 at 21:49

1 Answers1

1

The simplest approach to us old-fashioned types is to write a function:

int call_it() {
    return tempModel->GetTemp();
}

and store that function in the map in the question:

map<string, GetIntFunction> get_integer_map {
    { "temp", call_it }
};

A newer approach is to use a lambda:

map<string, GetIntFunction> get_integer_map {
    { "temp", [=]() { return tempModel->GetTemp(); }
};

Another approach (as suggested in the comment by Kamil Cuk) is to use std::function to bind the object and the function:

map<string, std::function<int()>> get_integer_map {
    { "temp", std::function<int()>(&TemperatureModel::GetTemp, tempModel) }
};

Caution: code written but not compiled; it may have errors.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165