我得到了一些示例代码从这里做一个C++可变参数模板:C++ 11可变参数模板
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);
彼得牛逼通过聊天发现了这个问题。它不会正确打印uint8_t,因为它将它视为ASCII。它需要被输入到例如uint16_t。当我有解决方案时,我会在这里发布。
你所有的警告和调试信息(编译'GCC -std = C++ 11 - 墙-g')?你使用了调试器('gdb')吗? – 2014-10-06 11:08:44
是的,我拥有所有这些标志。 – user1876942 2014-10-06 11:13:08
看起来[罚款](http://coliru.stacked-crooked.com/a/3cb5daa3767e0984)给我。 – Columbo 2014-10-06 11:14:53