简体   繁体   中英

c++ template pack expansion / variadic arguments

I've got this code, which does work:

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

However, I don't like having to specify the type twice. It seems that variadic templates would allow me to write something like:

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

Unfortunately, the documentation on pack expansion is too terse for me, and I have been unable to write a tfun template that will compile. Can someone show me how it's done?

Looks trivial.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM