Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making std::to_string work with void pointers, like operator<<? [closed]

I have some code which std::to_string()'s a variable whose type is a template parameter. Suppose the code is:

template <typename T> 
std::string foo(const T& t) { 
    return std::string("I got ") + std::to_string(t); 
}

Now, sometimes this parameter needs to be a void *; and I would like to get the address in the string, e.g. "I got 0xdeadbeef". No problem, right? I should get it just the same as if I did std::cout << my_ptr, right? ... Unfortunately for me, that's not the case. Well,

  • Is it "legitimate" for me to want the code above to work as I described?
  • Other than insisting on the use of a stream in foo(), is there anything better to do than to overload std::to_string for void*'s (using an std::stringstream in there for the operator<<) ?
like image 978
einpoklum Avatar asked Oct 27 '25 08:10

einpoklum


1 Answers

namespace my_to_str {
  using std::to_string;
  std::string to_string(void* ptr){
    // implement
  }
}

Now my_to_str::to_string can be extended with your own set of overloads, like void*.

like image 54
Yakk - Adam Nevraumont Avatar answered Oct 29 '25 00:10

Yakk - Adam Nevraumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!