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

Full text and comments »

  • Vote: I like it
  • +67
  • Vote: I do not like it