具有非模板的C ++可变参数模板函数

时间:2016-05-08 09:59:47

标签: c++ templates variadic-templates

所以我试图用一个可变参数模板替换多个类似的成员函数,因为函数都做同样的事情并将它们的一些参数转发给另一个函数。我试图替换这两个函数:

void function(T a, T b, double c, bool d = false)
{
    if (!isStateMemoryFixed) isStateMemoryFixed = true;
    helper.help(a, b, c);
    if (d) doStuff();
}
void function(T a, T b, T e, double c, bool d = false)
{
    if (!isStateMemoryFixed) isStateMemoryFixed = true;
    helper.help(a, b, e, c);
    if (d) doStuff();
}

用这个

template<typename... Ts>
void function(Ts... ts, bool d= false)
{
        if (!isStateMemoryFixed) isStateMemoryFixed = true;
        helper.help(ts...);
        if (d) doStuff();
}

并像之前那样称呼它:

void test()
{
    T a,b,e;
    double c;
    Obj obj;
    obj.function(a,b,e,c,true);
}

但是我收到一个错误:&#34;没有模板实例...匹配参数列表&#34;。 我是可变模板的新手,但我一直在阅读的内容表明我应该能够做到这一点。

1 个答案:

答案 0 :(得分:0)

正如Johannes Schaub和Bo Persson所说,可变参数必须位于列表的末尾。

所以,恕我直言,一个好于无解决方案(谨慎:未经测试)可以用这种方式重写函数(假设c参数是强制性的,甚至类型为double

template<typename... Ts>
void function(double c, bool d, Ts... ts)
{
        if (!isStateMemoryFixed) isStateMemoryFixed = true;
        helper.help(ts..., c);
        if (d) doStuff();
}

它不等同于:您放宽了false的默认d值。

通话

function(c, true, a, b, e);
相关问题