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

2

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<<) ?
c++
string
c++11
void-pointers
ostream

3 Answers

3
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*.

2

You can't overload std::to_string() for void*, so that's moot.

But you don't have to use std::to_string(). You could implement your own that just falls back to using a stringstream:

namespace N {
    template <class T>
    auto to_string(T const& val, int)
        -> decltype(std::to_string(val))
    {
        return std::to_string(val);
    }

    template <class T>
    std::string to_string(T const& val, ...)
    {
        std::ostringstream oss;
        oss << val;
        return val.str();
    }

    template <class T>
    std::string to_string(T const& val) {
        return to_string(val, 0);
    }
}

And this does allow for overloading N::to_string() with whatever specifics you want (e.g. if you want N::to_string(void* ) to do something special, just add another overload).

answered on Stack Overflow Jul 30, 2016 by Barry • edited Jul 30, 2016 by Barry
-1

You can make custom operator+ for void * cases:

std::string operator+(const std::string &str, const void *vstr){
    return str + std::string(reinterpret_cast<const char *>(vstr));
}
answered on Stack Overflow Jul 30, 2016 by LibertyPaul

User contributions licensed under CC BY-SA 3.0