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

How to write C++ function that accept unknown type&number of arguments?

本文关键字:数数 参数 函数 类型 C++ 何编写 未知      更新时间:2023-10-16

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

void Print(void* args ...)
{
   while(args)
     cout<<args[i];
}

函数应处理 int 和 (std::string 或 char*)

可能吗?

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

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

回答

将变量类型/参数数连接到一个字符串

无需为此编写自己的函数,只需使用std::stringstream

std::stringstream ss;
ss << intVar << stringVar << whatever;