繁体   English   中英

C ++ 11可变参数模板

[英]C++11 Variadic Template

我从此处获得了一些示例代码来制作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);

彼得T通过聊天发现了问题。 由于将uint8_t视为ASCII,因此无法正确打印。 需要将其类型强制转换为例如uint16_t。 如果有解决方案,请在此处发布。

在此处可以找到将可变参数模板与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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM