C ++模板包扩展/可变参数

时间:2018-08-09 10:44:47

标签: c++ variadic-templates

我有此代码,它可以正常工作:

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模板。有人可以告诉我它是怎么做的吗?

1 个答案:

答案 0 :(得分:3)

看起来微不足道。

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);
相关问题