Rating changes for last rounds are temporarily rolled back. They will be returned soon. ×

alvin777's blog

By alvin777, 10 years ago, translation, In English

I was playing with C++11 variadic templates and was able to produce line "a: 10, b: 5.1, s: asd" using just PR(a, b, s).

#define PR(...) pr(#__VA_ARGS__, __VA_ARGS__);

template<typename T>
void pr(const string& name, T t) {
    cout << name << ": " << t << endl;
}

template<typename T, typename ... Types>
void pr(const string& names, T t, Types ... rest) {
    auto comma_pos = names.find(',');
    cout << names.substr(0, comma_pos) << ": " << t << ", ";
    
    auto next_name_pos = names.find_first_not_of(" \t\n", comma_pos + 1);
    pr(string(names, next_name_pos), rest ...);
}

int a = 3;
float b = 5.1;
string s = "asd";

PR(a, b, s);
  • Vote: I like it
  • +67
  • Vote: I do not like it

»
10 years ago, # |
Rev. 3   Vote: I like it +17 Vote: I do not like it

It's really cool. Since, it's shorter to write, I also like using operator, function like operator<< function of std::ostream class with a variadic macro, but without a variadic template.

#include <iostream>
#include <string>
#define PR(a...)    do { std::cout << #a << ": "; pr,a; std::cout << '\n'; } while (false)

struct print {
    template <typename T>  
    print& operator,(const T& v) {
        std::cout << v << ", ";
        return *this;
    }
} pr;

int main()
{
    int a = 3;
    float b = 5.1;
    std::string s = "asd";

    PR(a, b, s);
}

a, b, s: 3, 5.1, asd,