传递显式空参数包
Pass explict empty arguments pack
我正在尝试按如下方式重载构造函数
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...)
。我该怎么做?
您不能显式调用模板构造函数 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...)
如果你想foo(1, 2)
调用可变模板构造函数,你想调用foo(int, int)
时你会写什么?
我的建议是:
声明嵌套 class;
指定模板构造器;
如果要调用可变参数模板构造函数,请在两个 int
之后追加嵌套 class 的对象。
您的代码应如下所示:
class Foo
{
public:
class Special {};
Foo(int, int) { /* ... */ }
template <typename... Args>
Foo(int, int, Args&&...) { /* ... */ }
template <typename... Args>
Foo(int, int, Special, Args&&...) { /* ... */ }
};
我正在尝试按如下方式重载构造函数
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...)
。我该怎么做?
您不能显式调用模板构造函数 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...)
如果你想foo(1, 2)
调用可变模板构造函数,你想调用foo(int, int)
时你会写什么?
我的建议是:
声明嵌套 class;
指定模板构造器;
如果要调用可变参数模板构造函数,请在两个
int
之后追加嵌套 class 的对象。
您的代码应如下所示:
class Foo
{
public:
class Special {};
Foo(int, int) { /* ... */ }
template <typename... Args>
Foo(int, int, Args&&...) { /* ... */ }
template <typename... Args>
Foo(int, int, Special, Args&&...) { /* ... */ }
};