【问题标题】:C++11 Variadic TemplateC++11 可变参数模板
【发布时间】: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
  • "但它只打印垃圾。"那是什么意思?只需发布完整的程序和你得到的输出。

标签: c++ c++11 variadic


【解决方案1】:

可以在此处找到通过 printf 使用可变参数模板的一个很好的示例:

http://msdn.microsoft.com/en-us/library/dn439779.aspx

void print() {
    cout << endl;
}

template <typename T> void print(const T& t) {
    cout << t << endl;
}

template <typename First, typename... Rest> void print(const First& first, const Rest&... rest) {
    cout << first << ", ";
    print(rest...); // recursive call using pack expansion syntax
}

int main()
{
    print(); // calls first overload, outputting only a newline
    print(1); // calls second overload

    // these call the third overload, the variadic template, 
    // which uses recursion as needed.
    print(10, 20);
    print(100, 200, 300);
    print("first", 2, "third", 3.14159);
}

【讨论】:

  • 只有链接的答案不是很好;链接腐烂。试着至少总结一下这篇文章。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
  • 2012-08-14
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多