user1876942
user1876942

Reputation: 1501

C++11 Variadic Template

I got some example code to make a c++ variadic template from here:

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

My code is as follows.

#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++;
    }
}

But it prints only junk. The main reason to use this is so I can print out std::string. How can I print out the correct values?

I call the function like this:

logDebug("Event is, event=%", value);

Peter T found the problem via chat. It does not print uint8_t correctly as it treats it like a ASCII. It needs to be type cast to e.g. uint16_t. When I have a solution, I will post it here.

Upvotes: 0

Views: 705

Answers (1)

Laura Maftei
Laura Maftei

Reputation: 1863

A good example for using variadic templates with printf can be found here:

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);
}

Upvotes: 1

Related Questions