c++ - c ++模板包扩展/可变参数
问题描述
我有这个代码,它确实有效:
auto thev = std::static_pointer_cast<Thevenin>(
add(new Thevenin(N("cntl"), N("gnd"), 1.0)));
auto det1 = std::static_pointer_cast<Detector>(
add(new Detector(N("vout"), N("gnd"), N("eout"), N("oout"), 0)));
auto det2 = std::static_pointer_cast<Detector>(
add(new Detector(N("cntl"), N("gnd"), N("ein"), N("oin"), 0)));
但是,我不喜欢必须指定类型两次。似乎可变参数模板允许我编写如下内容:
auto thev = tfun(Thevenin, N("cntl"), N("gnd"), 1.0);
auto det1 = tfun(Detector, N("vout"), N("gnd"), N("eout"), N("oout"), 0)));
auto det2 = tfun(Detector, N("cntl"), N("gnd"), N("ein"), N("oin"), 0)));
不幸的是,关于包扩展的文档对我来说太简洁了,我一直无法编写一个可以编译的 tfun 模板。有人可以告诉我它是如何完成的吗?
解决方案
看起来微不足道。
template<class RetVal, class... Args> inline auto tfun(Args &&...args) {
return std::static_pointer_cast<RetVal>(add(new RetVal(std::forward<Args>(args)...)));
}
auto thev = tfun<Thevenin>(N("cntl"), N("gnd"), 1.0);
推荐阅读
- angular - 如何在C3.js中更改y轴标签的标签字体大小和颜色
- python - 尝试根据基于 django 的投票应用教程安装我自己的包
- solidity - 不允许从“literal_string”到“字符串存储指针”的显式类型转换
- php - 我想根据下拉选择列表显示数据
- r - R Shiny:如何在 DT::renderDataTable 中添加分页
- unicode - 有多少种 Unicode 编码,它们都还在使用吗?
- javascript - 在指令和控制器中使用 ng-model
- javascript - JSP Json ArrayList 转 JavaScript 列表
- sqlite - SQLite 选择列名包含字符串的数据?
- c++ - 执行 strcpy 时出现分段错误错误