如何编写接受未知类型和参数数量的C++函数?

ita*_*mar 1 c++ argument-passing

我想写一个这种类型的函数:

void Print(void* args ...)
{
   while(args)
     cout<<args[i];
}
Run Code Online (Sandbox Code Playgroud)

funcdtion应该处理int和(std :: string或char*)

可能吗?

Ker*_* SB 6

您可以使用可变参数模板执行此操作:

void Print() { }

template <typename T, typename ...Args>
void Print(T const & t, Args const &... args)
{
    cout << t;
    Print(args...);
}
Run Code Online (Sandbox Code Playgroud)

  • @NeelBasu:单一类型,限制你如何调用它. (2认同)