Calling a function from a function pointer in an iterator

Refresh

November 2018

Views

108 time

3

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();

}

2 answers

1

объекты делают может сделать член-функцию вызова с членом-функцией-указателем , однако, ->*или .*операторы обязаны. Таким образом , вы , вероятно , хотели сделать:

// 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))();
}

Дополнительные скобки необходимы для того , чтобы сделать выражение действительных, иначе оператор старшинства пинки в и лишает законной силы его.


Другой вариант заключается в использовании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);
}

Смотрите , если эфир

0

Вы можете сделать что-то вроде:

auto it = actionsMap.find(compareVector[0]));
if (it != actionsMap.end()) {
    (this->*(it->second))();
}