【发布时间】:2014-10-06 11:07:11
【问题描述】:
我从这里获得了一些示例代码来制作 c++ 可变参数模板:
http://en.wikipedia.org/wiki/Variadic_template
我的代码如下。
#ifdef DEBUG
#define logDebug(x, ...) streamPrintf( x, ##__VA_ARGS__ );
#else
#define logDebug(x, ...)
#endif
void streamPrintf(const char *s);
template<typename T, typename... Args>
void streamPrintf(const char *s, T value, Args... args)
{
while (*s) {
if (*s == '%') {
if (*(s + 1) == '%') {
++s;
}
else {
std::cout << value;
streamPrintf(s + 1, args...);
return;
}
}
std::cout << *s++;
}
throw std::logic_error("extra arguments provided to printf");
}
void streamPrintf(const char *s)
{
while (*s) {
if (*s == '%') {
if (*(s + 1) == '%') {
++s;
}
else {
throw std::runtime_error("invalid format string: missing arguments");
}
}
std::cout << *s++;
}
}
但它只打印垃圾。使用它的主要原因是我可以打印出 std::string。如何打印出正确的值?
我这样调用函数:
logDebug("Event is, event=%", value);
Peter T 通过聊天发现了问题。它无法正确打印 uint8_t,因为它将其视为 ASCII。它需要类型转换为例如uint16_t。当我有解决方案时,我会在这里发布。
【问题讨论】:
-
您编译时是否包含所有警告和调试信息 (
gcc -std=c++11 -Wall -g)?您是否使用了调试器 (gdb)? -
是的,这些标志我都有。
-
在我看来只是fine。
-
"但它只打印垃圾。"那是什么意思?只需发布完整的程序和你得到的输出。