我想为函数创建一个C 模板,该模板允许根据任何数据类型的默认完整参数。我找到了一些示例,他们尝试在其中编码printf函数,但它不起作用(其中包括stdarg.h,我想要这样的东西:)
//util.cpp
#include <iostream>
template<typename ...Args>
void debugPrint(Args... args)
{
// pseudo: foreach args as a:
std::cout << a;
// pseudo: endforeach
std::cout << std::endl;
}
//util.hpp
template<typename ...Args> //?
void debugPrint(Args...);
//app.cpp
#include "util.hpp"
int main()
{
debugPrint("Hallo", " ", "Welt", 1, 2, "t", 2.3);
return 0;
}
想要控制台:Hallo Welt12 [TAB] 2.3
然后有一个带有stdarg.h
的审核 #include <stdarg.h>
void tprintf(const char* format) // base function
{
std::cout << format;
}
template<typename T, typename... Targs>
void tprintf(const char* format, T value, Targs... Fargs) // recursive function
{
for (; *format != ' '; format++) {
if (*format == '%') {
std::cout << value;
tprintf(format + 1, Fargs...); // recursive call
return;
}
std::cout << *format;
}
}
那怎么办?:(
感谢您的任何答案&lt; 3
与任何递归解决方案一样,您需要一个基本情况才能终止递归。在这种情况下,基本情况是没有剩下的论点要打印,在这种情况下,您什么也不做:
void debugPrint() { }
然后递归模板函数,该函数处理单个"第一个"参数,然后在其余的变异参数上递归:
template <typename FirstArg, typename ...Args>
void debugPrint(FirstArg arg, Args... args)
{
std::cout << arg;
debugPrint(args...);
}
将它们全部结合在一起:
#include <iostream>
void debugPrint() { }
template <typename FirstArg, typename ...Args>
void debugPrint(FirstArg arg, Args... args)
{
std::cout << arg;
debugPrint(args...);
}
int main()
{
debugPrint("Hallo", " ", "Welt", 1, 2, "t", 2.3);
}
输出:
Hallo Welt12 2.3
您可以使用折叠表达式来执行此操作(C 17):
template<typename... Args>
void debugPrint(Args const&... args) {
(std::cout << ... << args);
}
它将在扩展的表达式之间使用<<
扩展args
。不需要递归。
这是一个现场示例。