Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function from a function pointer in an iterator

I'm working inside a class called Level, where I'm storing pointers to two of the member functions of that class inside of a map. In another function called Update, I'm taking user input and then iterating through the map, first comparing keys, and then (attempting) to call the corresponding function using a function pointer. However, nothing I've tried thus far has worked (different iterators, using std::function instead of normal function pointers, and trying to call the function through a this pointer for the class object). Am I missing something obvious or am I taking an incorrect approach on this?

Relevant code below:

Level.h

// Create function pointers to store in the map
void(Level::*examine)() = &Level::Examine;
void(Level::*display)() = &Level::Display;

// Data structures
std::map<std::string, void(Level::*)()> actionsMap;

Level.cpp

void Level::Update(bool &gameState) {

// Display something to the user
std::cout << "You have reached the " << name << " level. Please perform an action.\n";

// Get user input
std::cin >> inputString;

// Split the string into words and store them in compareVector
compareVector = inputParser->Split(inputString, ' ');

// Check is the first noun can be handled by outputHandler functions
outputHandler->Compare(compareVector[0], gameState);

// Iterate through the actionsMap
for (auto it: actionsMap) {

    // If the key matches the first word, call the corresponding function
    if (it.first == compareVector[0]) {

        // Call the function - gives an error as it.second is not a pointer-to-function type
        it.second();

    }

}

// Clear the vector at the end
compareVector.clear();

}

like image 879
MattBT12 Avatar asked Nov 26 '25 23:11

MattBT12


1 Answers

objects make can make member-function calls via a member-function-pointer, however, the ->* or .* operators are required. Hence you probably wanted to do:

// If the key matches the first word, call the corresponding function
if (it.first == compareVector[0]) {

    // Call the function - gives an error as it.second is not a pointer-to-function type
    (this->*(it.second))();

    //Or
    ((*this).*(it.second))();
}

The extra parenthesis are required in order to make the expression valid, else operator precedence kicks in and invalidates it.


Another option is to use std::mem_fn

// If the key matches the first word, call the corresponding function
if (it.first == compareVector[0]) {

    // Call the function - gives an error as it.second is not a pointer-to-function type
    std::mem_fn(it.second)(this);
}

See if Live

like image 152
WhiZTiM Avatar answered Nov 29 '25 12:11

WhiZTiM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!