除了在 C++ 中使用 if walls 而不是其他东西之外,还有其他选择吗?
Is there any alternative to using if walls instead of something else in C++?
我正在做一些 C++,我的应用程序接受子命令,例如 ./my_app test 123
。
我是C++的半新手,在网上找不到任何东西所以我不知道哈哈。
例如 python 我会这样做:
#!/usr/bin/env python3
import sys
def test(num):
print(f"Test {num}")
subcommands = {"test": test}
subcommands[sys.argv[1](sys.argv[2])
有什么 C++ eq 吗?如果是这样,我应该使用它还是坚持 if-else_if-else?
看看std::map
/std::unordered_map
,例如:
#include <iostream>
#include <map>
#include <string>
void test(const std::string &value) {
std::cout << "Test " << value << std::endl;
}
using cmdFuncType = void(*)(const std::string &);
const std::map<std::string, cmdFuncType> subcommands = {
{"test": &test}
};
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "usage: program command value" << std::endl;
return 0;
}
auto iter = subcommands.find(argv[1]);
if (iter == subcommands.end()) {
std::cerr << "unknown command: " << argv[1] << std::endl;
return 0;
}
iter->second(argv[2]);
return 0;
}
这是您要实现的目标吗:
#include <string>
#include <functional>
#include <iostream>
#include <map>
void test(int num) {
std::cout << "Test " << num << "\n";
}
std::map<std::string, std::function<void(int)>> subcommands = {
{"test", test}
};
int main(int argc, char* argv[]) {
subcommands[argv[1]](std::atoi(argv[2]));
}
我正在做一些 C++,我的应用程序接受子命令,例如 ./my_app test 123
。
我是C++的半新手,在网上找不到任何东西所以我不知道哈哈。
例如 python 我会这样做:
#!/usr/bin/env python3
import sys
def test(num):
print(f"Test {num}")
subcommands = {"test": test}
subcommands[sys.argv[1](sys.argv[2])
有什么 C++ eq 吗?如果是这样,我应该使用它还是坚持 if-else_if-else?
看看std::map
/std::unordered_map
,例如:
#include <iostream>
#include <map>
#include <string>
void test(const std::string &value) {
std::cout << "Test " << value << std::endl;
}
using cmdFuncType = void(*)(const std::string &);
const std::map<std::string, cmdFuncType> subcommands = {
{"test": &test}
};
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "usage: program command value" << std::endl;
return 0;
}
auto iter = subcommands.find(argv[1]);
if (iter == subcommands.end()) {
std::cerr << "unknown command: " << argv[1] << std::endl;
return 0;
}
iter->second(argv[2]);
return 0;
}
这是您要实现的目标吗:
#include <string>
#include <functional>
#include <iostream>
#include <map>
void test(int num) {
std::cout << "Test " << num << "\n";
}
std::map<std::string, std::function<void(int)>> subcommands = {
{"test", test}
};
int main(int argc, char* argv[]) {
subcommands[argv[1]](std::atoi(argv[2]));
}