使用variadic模板的C 通用命令解析器
C++ Generic command parser using variadic templates
我正在尝试编写某种命令处理程序,该命令处理程序可以使istringstreams化,自动将令牌自动转换为特定类型的变量,并以转换变量为参数调用回调函数。这是我的代码的简化版本:
void Callback(int x, char y, float z) {
// do whatever
// note: For simplicity, I use a callback with a fixed signature
// here. In my actual implementation, the callback can be
// called with any number and types of arguments - but that
// I have solved already.
}
template<typename T>
T GetNextArgument(std::istringstream& strm) {
// get one token from the input stream and convert it to the required type
T val;
strm >> val;
return val;
}
template<typename ...Args>
void ParseAndExecute(std::istringstream& input_stream) {
Callback(GetNextArgument<Args>(input_stream)...);
}
int main() {
std::istringstream strm("15 a 17.3");
ParseAndExecute(strm);
return 0;
}
我遇到的问题是,参数包扩展后的ParseAndExecute()
功能如下:
void ParseAndExecute(std::istringstream& strm) {
Callback(GetNextArgument<int>(strm),
GetNextArgument<char>(strm),
GetNextArgument<float>(strm));
}
由于未定义对参数的评估顺序,因此代币可以以不正确的顺序从流中获取(在我的情况下,它们始终是)。相反,我需要扩展才能给我更多类似的东西:
void ParseAndExecute(std::istringstream& strm) {
int a1 = GetNextArgument<int>(strm);
char a2 = GetNextArgument<char>(strm);
float a3 = GetNextArgument<float>(strm);
Callback(a1, a2, a3);
}
,但我看不到如何通过参数包扩展来实现这一目标。也许有一个递归模板...?还是您还有其他建议以实现类似的功能?
struct Caller {
template<class...Args>
Caller(Args&&... args) { Callback(std::forward<Args>(args)...); }
};
template<typename ...Args>
void ParseAndExecute(std::istringstream& input_stream) {
Caller{GetNextArgument<Args>(input_stream)...};
}
您可以使用带有列表初始化的中间std::tuple
,因为在这种情况下是必须的:
std::tuple<Args...> tuple_args = {GetNextArgument<Args>(input_stream)... };
std::apply([](auto&&... args) {
Callback(std::forward<decltype(args)>(args)... );
}, std::move(tuple_args));
,如果Callback
没有您提到的固定签名,则必须使用lambda。
相关文章:
- 从命令行c++发送文本文件名
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 使用QProcess执行命令,并将结果存储在QStringList中
- 数组长度,为什么从命令行获取时不能使用它?
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- clang整洁10忽略了我的NOLINT命令
- Variadic模板未编译
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 如何处理linux终端中带有负号(-)的C++中的命令行参数
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用VS Code和CMake Tools运行自定义命令
- variadic模板中的模板参数推导失败
- 如何使用ESP8266向谷歌主页发送命令
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 通过 Openssl 命令行加密,通过 c++ 解密
- CMake "--target install"无需"--build"命令行
- 使用variadic模板的C 通用命令解析器