首页 > 解决方案 > 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 模板。有人可以告诉我它是如何完成的吗?

标签: c++variadic-templates

解决方案


看起来微不足道。

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);

推荐阅读