传递显式空参数包

时间:2019-07-13 12:11:06

标签: c++ parameter-passing variadic-templates

我正在尝试按如下方式重载构造函数

struct foo
{
    foo(int, int);

    template<typename... Args>
    foo(int, int, Args... args);
}

foo(int, int)的行为不同于foo(int, int, empty_arguments_pack)。 我希望foo(1, 2)呼叫foo(int, int),而类似foo(1, 2, )的呼叫foo(int, int, Args...)。我该怎么办?

2 个答案:

答案 0 :(得分:2)

您不能将模板构造函数显式调用为foo<>(1, 2) /*Illegal*/

您可以创建其他带标签的重载foo(special_tag, int, int/*, Args...*/)来解决您的问题

struct special_tag{};

class foo
{
public:
    template<typename... Args>
    foo(special_tag, int i1, int i2, Args... args) { /**/}

    foo(int, int) { /*...*/}

    // And possibly
    template<typename... Args>
    foo(int i1, int i2, Args... args) : foo(special_tag{}, i1, i2, args...) { /*...*/}
};

现在,您可以使用:

foo(1, 2); // foo(int, int)
foo(special_tag{}, 1, 2); // foo(special_tag, int, int, Args...)
foo(special_tag{}, 1, 2, 3); // foo(special_tag, int, int, Args...)
// And possibly:
foo(1, 2, 3); // foo(int, int, Args...) so foo(special_tag, int, int, Args...)

答案 1 :(得分:0)

如果您希望foo(1, 2)调用可变参数模板构造函数,那么当您想调用foo(int, int)时会写什么?

我的建议是:

  1. 声明一个嵌套类;

  2. 指定模板构造函数;

  3. 如果要调用可变参数模板构造函数,则在两个int之后追加嵌套类的对象。

您的代码应如下所示:

class Foo
{
public:
    class Special {};

    Foo(int, int) { /* ... */ }

    template <typename... Args>
    Foo(int, int, Args&&...) { /* ... */ }

    template <typename... Args>
    Foo(int, int, Special, Args&&...) { /* ... */ }
};