0

I am implementing a print debugging system for a school assignment. I apologize if the answer is obvious, I am still learning c++.

I want to create a function, that takes three parameters: an error, a variable name, and the variable itself, and logs such information somewhere that can be viewed later. It would work like this:

int bad_variable = 2;
debug_log("Variable unexpected value", "bad_variable", bad_variable);

The problem is, I would have no idea what type of variable to expect when parsing bad_variable to debug_log, and therefore it cannot be defined. To my knowledge there is no way to parse a variable of an unknown type... however the c++ standard library does just that in the function std::to_string!

std::to_string could be the answer to my problem, I could just pass my bad_variable into std::to_string to convert it to a string, having debug_log expect the output string. However, I would have to type std::to_string every time I called the log function.

debug_log("Variable unexpected value", "bad_variable", std::to_string(bad_variable));

This to me seems like a patchwork solution to something that must have a simpler answer. I want to keep this debug function as simplistic as possible. How could I create a function that takes an unknown variable type, and generates a string containing the value of that variable?

Ricky Gonce
  • 105
  • 1
  • 10
  • look up templates. but keep in mind that these are running at compile time .. not runtime – Daniel Jour Jan 03 '20 at 17:54
  • It seems that you want either *function overloading* or (more likely) *function templates*. You should be able to find information about these in your instruction material or other introductional book to C++. (though maybe in an advanced section) – walnut Jan 03 '20 at 17:55
  • 1
    @DanielJour You mean that the type at each call site is determined at compile-time. They are not evaluated at compile-time. – walnut Jan 03 '20 at 17:56
  • Function overloading is better solution, however templates seem to be the best solution. I will read more into templates. – Ricky Gonce Jan 03 '20 at 18:07

1 Answers1

1

How could I create a function that takes an unknown variable type, and generates a string containing the value of that variable?

Since you've tagged this question C++, one nice way of doing so is by using templates:

     template<typename t_value>
      string convToString(t_value value)  {
       std::ostringstream oss; 
       oss << value;  
       return oss.str();
     }
H S
  • 1,211
  • 6
  • 11
  • That's assuming that the type in question can be streamed to a stream. That is *not* universally true and certainly doesn't match OPs question of " Passing a variable of any type ..." (But that's probably impossible anyway). – Jesper Juhl Jan 03 '20 at 18:06