【问题标题】:Calling a function from a function pointer in an iterator从迭代器中的函数指针调用函数
【发布时间】:2018-02-10 22:46:46
【问题描述】:

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

相关代码如下:

级别.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();

}

【问题讨论】:

  • 你可能想做:(this-&gt;*(it.second))()
  • 是的,这正是我需要做的。我猜我只是遗漏了一些明显的东西;谢谢!

标签: c++ pointers c++14


【解决方案1】:

objects make 可以通过 member-function-pointer 进行 member-function 调用,但是,-&gt;*.*操作员是必需的。因此,您可能想要这样做:

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

为了使表达式有效,额外的括号是必需的,否则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
    std::mem_fn(it.second)(this);
}

看看Live

【讨论】:

    【解决方案2】:

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多