具有重复类型的 C++ 可变参数模板

C++ variadic templates with repeating types

是否可以编写函数签名类似于

的可变参数模板或折叠表达式
void f(int, string, int, string, ...)

这种风格在 python 中非常流行且用户友好,但我无法在 C++ 中使用它。特别是我会用它来为绘图函数提供数据,然后是标签。

编辑:为了扩展,我想这样调用函数:

f(5, "first number");
f(5, "first number", 6, "second number");

并带有 4、6 或 ... 2*n 个参数。

你可以这样写一个可变函数:

template<typename ...Ts>
void f(int data, string const &label, Ts&&... rest)
{
  process(data, label);
  f(std::forward<Ts>(rest...));
}

有一个基本案例:

void f() {}

终止递归。

现在只能调用以下形式:

f(1, "hi");           // ok
f(1, "hi", 2, "bye"); // ok
// etc

将编译,而:

f(1);          // error
f("hi");       // error
f(1, "hi", 2); // error

不会。

例如,定义两个重载:

void f() {}

template<class... Ts>
void f(int i, std::string s, Ts... ts) {
    f(std::move(ts)...); // static recursion
}