Search code examples
c++templatesc++11pretty-print

Pass the name of a variable to a function in C++


I'm trying to create a printing function. I want it to be able to take in a list of variables and print out both their value and their name. So far, I have the following code:

std::ostream& debug_values(std::ostream& out);  

template <typename V, typename... R>
std::ostream& debug_values(
    std::ostream& out, const V& value, const R&... remaining) {
  out << value << ", ";
  debug_values(out, remaining...);
  return out;
}

This works, but it only prints out the values. For example:

ostream out;
int i1 = 1;
int i2 = 2;
debug_values(out, i1, i2) //Will print 1, 2

Instead, I would like debug_values to print out the following:

debug_values(out, i1, i2); //i1: 1, i2: 2

Is there a way to do this in C++? If so, how?


Solution

  • You can not use pure C++ to achieve that. However you can use the preprocessor to achieve what you want

    #define PP( expr ) std::cout<<#expr<<" "<<expr<<std::endl;
    

    See it live here : http://ideone.com/UopOni

    Alternatively, Qt's QObjects can have this kind of named variables called properties

    This solution is useful for debugging or logging, but it's not very pretty.