如何编写C++接受未知类型和参数数量的函数?
How to write C++ function that accept unknown type&number of arguments?
我想写一个这种类型的函数:
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;
相关文章:
- C++函数模板需要 &for 数组参数
- C++ 数组参数不起作用
- 使用数组参数进行函数专用化
- 为什么我的数组参数的方法无法正常工作?(C )
- SWIG - Java 代理类数组参数
- 在 gcc 中使用数组参数编译外部"c"代码
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 基于模板参数的模板类力数的参数
- 如何根据数组参数项类型重载 IDL 中的函数
- 引用谷歌测试/模拟框架中的数组参数
- 比特菲尔德,标志数为参数
- C++将数组参数传递给函数
- 字符星形数组参数未正确终止
- 如何将德尔菲的"字符串数组"参数翻译成C++?
- 为什么 gcc 无法推断数组参数的模板化大小?(C++11)
- 使用 const char 数组参数分析 constexpr 显示运行时执行
- C++指针数组参数
- 固定大小的多维数组参数
- 为什么数组参数被视为常量数组
- 如何在pgsql中格式化数组参数