How can I format a null pointer of any type, preferably including immediate nullptr, on out stream so it prints out like 0x000000000000 or even just 0x0 but something resembling an address value instead of a senseless 0 or terminate or whatever non-address-like? //(nil) or (null) I could accept too if not using printf.
You can make a pointer formatter, which can do the formatting in whatever way you prefer.
For example:
#include <cstdint>
#include <iomanip>
#include <ios>
#include <iostream>
#include <sstream>
#include <string>
static auto Fmt(void const* p) -> std::string {
auto value = reinterpret_cast<std::uintptr_t>(p);
constexpr auto width = sizeof(p) * 2;
std::stringstream ss;
ss << "0x" << std::uppercase << std::setfill('0') << std::setw(width) << std::hex << value;
return ss.str();
}
int main() {
char const* p = nullptr;
std::cout << Fmt(p) << "\n";
p = "Hello";
std::cout << Fmt(p) << "\n";
}
You can just overload << operator for void pointer.
#include <iostream>
struct Foo {
void bar() {}
};
std::ostream& operator<<(std::ostream& stream, void *p) {
return stream << 0 << 'x' << std::hex << reinterpret_cast<size_t>(p) << std::dec;
}
int main() {
Foo foo;
Foo *p = &foo;
std::cout << p << std::endl;
p = nullptr;
std::cout << p << std::endl;
}
Or add a wrapper which is more flexible, since you can use both approaches, but will require a bit more typing.
#include <iostream>
struct Foo {
void bar() {}
};
struct Pointer_wrapper {
void *p_;
explicit Pointer_wrapper(void *p) :p_(p) {}
};
std::ostream& operator<<(std::ostream& stream, const Pointer_wrapper& w) {
return stream << 0 << 'x' << std::hex << reinterpret_cast<size_t>(w.p_) << std::dec;
}
using pw = Pointer_wrapper;
int main() {
Foo foo;
Foo *p = &foo;
std::cout << pw(p) << std::endl;
p = nullptr;
std::cout << pw(p) << std::endl;
}
Related
Is only the way to modify, not replace, an object stored as std::any is to declare changeable data mutable? E.g. to avoid creation and copy of class S instances:
#include <iostream>
#include <vector>
#include <any>
#include <string>
struct S {
mutable std::string str;
S(S&& arg) : str(std::move(arg.str)) { std::cout << ">> S moved" << std::endl; }
S(const S& arg) : str(arg.str) { std::cout << ">> S copied" << std::endl; }
S(const char *s) : str(s) { std::cout << ">> S created" << std::endl; }
S& operator= (const S& arg) { str = arg.str; return *this; }
S& operator= (S&& arg) { str = std::move(arg.str); return *this; }
virtual ~S() { std::cout << "<< S destroyed" << std::endl; }
};
int main() {
std::vector<std::any> container;
container.emplace_back(S("Test 1"));
std::any_cast<const S&>(container[0]).str = "Test 2";
for (const auto& a : container) {
std::cout << a.type().name() << ", "
<< std::any_cast<const S&>(a).str << std::endl;
}
}
You can any_cast with non-const reference:
std::any_cast<S&>(container[0]).str = "Test 2";
Demo
or
std::any a = 40;
std::any_cast<int&>(a) += 2;
std::cout << std::any_cast<int>(a) <<std::endl;
Demo
nope.
The issue is here.
std::any_cast<const S&>(container[0]).str = "Test 2";
you are trying to change constant data
I have class A which has methods void fun(int, int) and void fun1(int, int). These are non-static methods.
struct A {
void fun(int,int){}
void fun1(int,int){}
};
Now inside class B I want to store pointer to one of the method.
Which means object1 of B will have pointer to fun and object2 of B will have pointer to fun1.
Now my set_handler() and pointer to handler has to be generic.
One way is to use function pointers.
So that that I can use void(A::*pointer)(int,int) which can store address of fun or fun1.
struct B {
typedef void(A::*pointer)(int,int);
pointer f;
void set_handler(pointer p) { f = p; }
};
int main() {
{
B object1;
object2.set_handler(&A::fun);
}
{
B object2;
object2.set_handler(&A::fun1);
}
}
I was looking into boost::bind() but it needs specific name. How do I use boost here?
I malled your question into running code that actually does something with the pointer - so we know when the goal has been achieved:
Live On Coliru
#include <iostream>
struct A {
void fun(int a, int b) { std::cout << __FUNCTION__ << "(" << a << "," << b << ")" << std::endl; }
void fun1(int a, int b) { std::cout << __FUNCTION__ << "(" << a << "," << b << ")" << std::endl; }
};
struct B {
typedef void (A::*pointer)(int, int);
pointer f;
void set_handler(pointer p) { f = p; }
void run(A& instance) {
(instance.*f)(42, 42);
}
};
int main() {
B object1;
B object2;
object1.set_handler(&A::fun);
object2.set_handler(&A::fun1);
A a;
object1.run(a);
object2.run(a);
}
Prints
fun(42,42)
fun1(42,42)
Using boost::function or std::function
You have to allow for the instance argument (the implicit this parameter):
Live On Coliru
struct B {
using function = std::function<void(A&, int, int)>;
function f;
void set_handler(function p) { f = p; }
void run(A& instance) {
f(instance, 42, 42);
}
};
Which prints the same output. Of course you can use boost::function and boost::bind just the same
What about bind?
Bind comes in when you want to adapt the function signatures. So, e.g. you want to bind to any instance of A& without actually passing it into run():
Live On Coliru
#include <iostream>
#include <functional>
struct A {
std::string name;
void fun(int a, int b) { std::cout << "name:" << name << " " << __FUNCTION__ << "(" << a << "," << b << ")" << std::endl; }
void fun1(int a, int b) { std::cout << "name:" << name << " " << __FUNCTION__ << "(" << a << "," << b << ")" << std::endl; }
};
struct B {
using function = std::function<void(int, int)>;
function f;
void set_handler(function p) { f = p; }
void run() {
f(42, 42);
}
};
int main() {
B object1;
B object2;
A a1 {"black"};
A a2 {"white"};
{
using namespace std::placeholders;
object1.set_handler(std::bind(&A::fun, &a1, _1, _2));
object2.set_handler(std::bind(&A::fun1, &a2, _1, _2));
}
object1.run();
object2.run();
}
Which prints:
name:black fun(42,42)
name:white fun1(42,42)
More Goodness
From c++ you can do without bind and its pesky placeholders (there are other caveats, like bind storing all arguments by value). Instead, you may use lambdas:
Live On Coliru
#include <iostream>
#include <functional>
struct A {
std::string name;
void fun(int a, int b) { std::cout << "name:" << name << " " << __FUNCTION__ << "(" << a << "," << b << ")" << std::endl; }
void fun1(int a, int b) { std::cout << "name:" << name << " " << __FUNCTION__ << "(" << a << "," << b << ")" << std::endl; }
};
struct B {
using function = std::function<void(int, int)>;
function f;
void set_handler(function p) { f = p; }
void run() {
f(42, 42);
}
};
int main() {
B object1;
B object2;
object1.set_handler([](int a, int b) {
A local_instance {"local"};
local_instance.fun(a*2, b*3); // can even do extra logic here
});
A main_instance {"main"};
object2.set_handler([&main_instance](int a, int b) {
main_instance.fun1(a, b); // can even do extra logic here
});
object1.run();
object2.run();
}
Prints
name:local fun(84,126)
name:main fun1(42,42)
The code that works is the following:
#include <boost/variant.hpp>
#include <string>
#include <map>
#include <iostream>
int main(int argc, char** argv) {
std::map<std::string, boost::variant<int, std::string> > values;
values["a"] = 10;
values["b"] = "bstring";
values["c"] = "cstring";
for (const auto &p : values) {
std::cout << p.first << " = ";
if (p.second.type() == typeid(std::string)) {
std::cout << boost::get<std::string>( p.second ) << " (found string)" << std::endl;
} else if ( p.second.type() == typeid(int)) {
std::cout << boost::get<int>( p.second ) << " (found int)" << std::endl;
} else if ( p.second.type() == typeid(bool)) {
std::cout << boost::get<bool>( p.second ) << " (found bool)" << std::endl;
} else {
std::cout << " not supported type " << std::endl;
}
}
}
The output (g++ test.cpp -std=c++11):
a = 10
b = bstring
c = cstring
The code that does not work is exactly the same, except the line that defines the std::map
modifying the line of the map definition to:
std::map<std::string, boost::variant<int, std::string, bool> > values;
the output is different:
a = 10
b = c =
The if statement that refers to std::string comparison does not succeed. What is the problem?
In your code, values["b"] = "bstring"; creates a bool value, when both std::string and bool are in the variant type.
A fix is values["b"] = std::string("bstring");.
Or, in C++14:
using namespace std::string_literals;
values["b"] = "bstring"s;
It is a well-known annoyance that string literals better convert to bool than to std::string:
#include <iostream>
#include <string>
void f(std::string) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
void f(std::string const&) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
void f(bool) { std::cout << __PRETTY_FUNCTION__ << '\n'; }
int main() {
f("hello");
}
Outputs:
void f(bool)
This question already has answers here:
How can I print 0x0a instead of 0xa using cout?
(9 answers)
Closed 6 years ago.
Say I have a dword I want to output in hex with std::cout and left-pad with zeros, so 0xabcd will be shown as 0x0000abcd. It seems like you would have to do this:
uint32_t my_int = 0xabcd;
std::cout << "0x" << std::hex << std::setw(8) << std::setfill('0')
<< my_int << std::endl;
This seems ridiculous for something that can be accomplished in C with printf("0x%08X\n", my_int);. Is there any way to make this shorter while still using std::cout for output (besides using namespace std)?
I suppose you can write a "stream manipulator". This is useful if you have multiple hex numbers you want to print in this format. This is clearly not an ideal solution, but using a wrapper type you can make your own "format flag" to toggle it. See Sticky custom stream manipulator for more information.
#include <iostream>
#include <iomanip>
static int const index = std::ios_base::xalloc();
std::ostream& hexify(std::ostream& stream) {
stream.iword(index) = 1;
return stream;
}
std::ostream& nohexify(std::ostream& stream) {
stream.iword(index) = 0;
return stream;
}
struct WrapperType {
uint32_t _m;
public:
WrapperType(uint32_t m) : _m(m)
{
}
uint32_t getm() const
{
return _m;
}
};
std::ostream& operator<< (std::ostream& os, const WrapperType& t) {
if (os.iword(index))
return os << "0x" << std::hex << std::setw(8) << std::setfill('0') << t.getm();
else
return os << t.getm();
}
int main()
{
WrapperType my_int{0xabcd};
std::cout << hexify << my_int << my_int;
std::cout << nohexify << my_int;
}
I would not change the (global) flags of a stream, just a manipulator:
#include <iostream>
#include <iomanip>
#include <limits>
template <typename T>
struct Hex
{
// C++11:
// static constexpr int Width = (std::numeric_limits<T>::digits + 1) / 4;
// Otherwise:
enum { Width = (std::numeric_limits<T>::digits + 1) / 4 };
const T& value;
const int width;
Hex(const T& value, int width = Width)
: value(value), width(width)
{}
void write(std::ostream& stream) const {
if(std::numeric_limits<T>::radix != 2) stream << value;
else {
std::ios_base::fmtflags flags = stream.setf(
std::ios_base::hex, std::ios_base::basefield);
char fill = stream.fill('0');
stream << "0x" << std::setw(width) << value;
stream.fill(fill);
stream.setf(flags, std::ios_base::basefield);
}
}
};
template <typename T>
inline Hex<T> hex(const T& value, int width = Hex<T>::Width) {
return Hex<T>(value, width);
}
template <typename T>
inline std::ostream& operator << (std::ostream& stream, const Hex<T>& value) {
value.write(stream);
return stream;
}
int main() {
std::uint8_t u8 = 1;
std::uint16_t u16 = 1;
std::uint32_t u32 = 1;
std::cout << hex(unsigned(u8), 2) << ", " << hex(u16) << ", " << hex(u32) << '\n';
}
My C++ is rusty, but how about using Boost formatting: http://www.boost.org/doc/libs/1_37_0/libs/format/index.html
I am playing with pointer-to-members and decided to actually print the values of the pointers. The result was not what I expected.
#include <iostream>
struct ManyIntegers {
int a,b,c,d;
};
int main () {
int ManyIntegers::* p;
p = &ManyIntegers::a;
std::cout << "p = &ManyIntegers::a = " << p << std::endl; // prints 1
p = &ManyIntegers::b;
std::cout << "p = &ManyIntegers::b = " << p << std::endl; // prints 1
p = &ManyIntegers::c;
std::cout << "p = &ManyIntegers::c = " << p << std::endl; // prints 1
p = &ManyIntegers::d;
std::cout << "p = &ManyIntegers::d = " << p << std::endl; // prints 1
return 0;
}
Why is the value of p always 1? Shouldn't the value of p somehow reflect which class member it points to?
As everyone has said, ostream doesn't have the appropriate operator<< defined.
Try this:
#include <cstddef>
#include <iostream>
struct Dumper {
unsigned char *p;
std::size_t size;
template<class T>
Dumper(const T& t) : p((unsigned char*)&t), size(sizeof t) { }
friend std::ostream& operator<<(std::ostream& os, const Dumper& d) {
for(std::size_t i = 0; i < d.size; i++) {
os << "0x" << std::hex << (unsigned int)d.p[i] << " ";
}
return os;
}
};
#include <iostream>
struct ManyIntegers {
int a,b,c,d;
};
int main () {
int ManyIntegers::* p;
p = &ManyIntegers::a;
std::cout << "p = &ManyIntegers::a = " << Dumper(p) << "\n";
p = &ManyIntegers::b;
std::cout << "p = &ManyIntegers::b = " << Dumper(p) << "\n";
p = &ManyIntegers::c;
std::cout << "p = &ManyIntegers::c = " << Dumper(p) << "\n";
p = &ManyIntegers::d;
std::cout << "p = &ManyIntegers::d = " << Dumper(p) << "\n";
return 0;
}
Standard ostream operator<< has no overload for pointer to member, so you pointer has been implicitly converted to bool.
p actually contains offset in object. Printing them prints implicit converted bool value true or false if they really contains some offset or not respectively. Conversion happens due to the fact that ostream's insertion member doesn't have any overload for pointers to members.
There is no overload of operator<< which takes pointer-to-member as argument. So if you try printing pointer-to-member, it implicitly converts into true which gets passed to the overload which takes bool as argument, and it prints 1 corresponds to true.
If you use std::boolalpha stream-manipulator, it will print true instead of 1:
std::cout << std::boolalpha << "p = &ManyIntegers::a = " << p ;
//^^^^^^^^^^^^^^
Output (see at ideone):
p = &ManyIntegers::a = true
A member pointer isn't necessarily a numeric value, more often than not it will be a struct or something the like. I don't think there is a way to obtain a value from a member pointer, but even if there is I don't see how that would be useful.
Here's a fully standards-compliant implementation to show the in-memory representation of the pointer-to-members:
#include <iostream>
#include <iomanip>
template<int... I> struct index_tuple { using succ = index_tuple<I..., sizeof...(I)>; };
template<int I> struct indexer { using type = typename indexer<I - 1>::type::succ; };
template<> struct indexer<0> { using type = index_tuple<>; };
template<typename T> typename indexer<sizeof(T)>::type index(const T &) { return {}; }
template<typename T> class dumper {
unsigned char buf[sizeof(T)];
friend std::ostream &operator<<(std::ostream &os, const dumper &o) {
std::ios_base::fmtflags flags{os.flags()};
std::copy_n(o.buf, sizeof(T),
std::ostream_iterator<int>(os << std::hex << std::showbase, " "));
return os << std::setiosflags(flags);
}
template<int... I> dumper (const T &t, index_tuple<I...>):
buf{reinterpret_cast<const unsigned char *>(&t)[I]...} {}
public:
dumper(const T &t): dumper(t, index(t)) {}
};
template<typename T> dumper<T> dump(const T &t) { return {t}; }
struct ManyIntegers {
int a,b,c,d;
};
int main () {
std::cout << "p = &ManyIntegers::a = " << dump(&ManyIntegers::a) << std::endl;
std::cout << "p = &ManyIntegers::b = " << dump(&ManyIntegers::b) << std::endl;
std::cout << "p = &ManyIntegers::c = " << dump(&ManyIntegers::c) << std::endl;
std::cout << "p = &ManyIntegers::d = " << dump(&ManyIntegers::d) << std::endl;
}
Output is as expected:
p = &ManyIntegers::a = 0 0 0 0
p = &ManyIntegers::b = 0x4 0 0 0
p = &ManyIntegers::c = 0x8 0 0 0
p = &ManyIntegers::d = 0xc 0 0 0