首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++11可变模板

C++11可变模板
EN

Stack Overflow用户
提问于 2014-10-06 19:07:11
回答 1查看 666关注 0票数 0

我从这里获得了一些示例代码来制作c++可变模板:

http://en.wikipedia.org/wiki/Variadic_template

我的代码如下。

代码语言:javascript
复制
#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。如何打印出正确的值?

我像这样调用函数:

代码语言:javascript
复制
logDebug("Event is, event=%", value);

Peter T通过聊天发现了这个问题。它无法正确打印uint8_t,因为它将其视为ASCII码。它需要被类型转换为例如uint16_t。当我有一个解决方案时,我会在这里发布它。

EN

回答 1

Stack Overflow用户

发布于 2014-10-06 20:11:00

在这里可以找到一个结合使用可变模板和printf的好例子:

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

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26214929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档