从迭代器中的函数指针调用函数

时间:2017-09-01 20:23:25

标签: c++ pointers c++14

我在一个名为Level的类中工作,我在那里存储指向该类内部两个成员函数的指针。在另一个名为Update的函数中,我接受用户输入然后遍历映射,首先比较键,然后(尝试)使用函数指针调用相应的函数。但是,到目前为止我没有尝试过任何工作(不同的迭代器,使用std :: function而不是普通的函数指针,并尝试通过this指针调用该类函数)。我错过了一些明显的东西,还是我对此采取了不正确的方法?

以下相关代码:

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 个答案:

答案 0 :(得分:1)

objects make可以通过 member-function-pointer 进行成员函数调用,但->*或{ {1}}运营商是必需的。因此你可能想做:

.*

为了使表达式有效,需要使用额外的括号,否则operator precedence将启动并使其无效。

另一个选项是使用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
    (this->*(it.second))();

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

查看是否Live

答案 1 :(得分:0)

您可以执行以下操作:

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