C++:使用参数包显式调用函数重载
C++: Explicitly call function overload with param pack
如何使用参数包调用函数的重载版本?这大致是我想做的:
void foo(int x=5) {
// Call foo<Args...>(x) here
}
template <typename... Args>
void foo(int x, Args&&... args) {
}
这可能吗?还是我需要不同的函数名称?
您可以通过显式指定模板参数来调用模板版本。如果没有要指定的模板参数,您可以指定空列表。例如
template <typename... Args>
void foo(int x, Args&&... args) {
}
void foo(int x=5) {
foo<>(x);
}
由于模板函数采用 int
作为非默认参数,因此非模板函数采用 int
根本没有多大意义。传入 int
值将同时满足这两个函数,从而导致歧义。所以我建议完全去掉非模板函数的 int
参数:
template <typename... Args>
void foo(int x, Args&&... args) {
...
}
void foo() {
foo<>(5);
}
如何使用参数包调用函数的重载版本?这大致是我想做的:
void foo(int x=5) {
// Call foo<Args...>(x) here
}
template <typename... Args>
void foo(int x, Args&&... args) {
}
这可能吗?还是我需要不同的函数名称?
您可以通过显式指定模板参数来调用模板版本。如果没有要指定的模板参数,您可以指定空列表。例如
template <typename... Args>
void foo(int x, Args&&... args) {
}
void foo(int x=5) {
foo<>(x);
}
由于模板函数采用 int
作为非默认参数,因此非模板函数采用 int
根本没有多大意义。传入 int
值将同时满足这两个函数,从而导致歧义。所以我建议完全去掉非模板函数的 int
参数:
template <typename... Args>
void foo(int x, Args&&... args) {
...
}
void foo() {
foo<>(5);
}