【发布时间】:2019-03-02 09:36:23
【问题描述】:
当在main.cpp while 循环中读取它们时,我正在尝试从test.txt 调用fA 和fB。
test.txt
fA()
fB("fB")
main.cpp
#include <iostream>
#include <fstream>
#include <string>
void fA() {
std::cout << "fA called" << std::endl;
}
void fB(std::string b) {
std::cout << b << std::endl;
}
int main() {
std::ifstream file;
file.open("test.txt");
if (file.is_open()) {
std::string line;
while (std::getline(file, line))
std::cout << line << std::endl;
}
file.close();
}
尽管fA 和fB 做类似的事情并且可以在示例中编写为一个函数,但实际上这些函数可以做完全不同的事情。因此我需要按名称调用该函数。
调用者具有带有参数类型的函数声明。
没有库,除了 STL。
【问题讨论】:
-
到目前为止,您尝试了哪些方法来解决问题?您对可能的解决方案有什么问题,或者您为什么不喜欢您找到的解决方案?已经有关于该主题的各种问题,例如:How to call a function by its name (std::string) in C++?、Call function by name given as a string、Calling a Function From a String With the Function’s Name in C++ ...(以及更多)
-
最简单的方法可能是使用正则表达式解析从文件中读取的行以提取函数名称和参数,并在 if else if 级联中调用相应的函数。不,我没有给你一个示例代码如何做到这一点,这是你编写它的一部分。
标签: c++