print value of void pointer

Dear Guys,

Below is the case:

in main program:
int a = 999;
int b = "abcde";
void* p;

p = &a; printPointerValue(p);
p = &b; printPointerValue(p);

void printPointerValue(void* p) {
//... i tried *((int*)p) --> it works for int (static casting)
// i dont want to use switch and put one by one
}

I want to make printPointerValue print value of void* p without static casting, but instead dynamic casting. Does anyone has other idea to make this happened ? or the core logic ?

Because in my logic, in assembler code, we all know there is no type for all those data (all are void type), but I dont know how C++ compiler build the binary code to differentiate those data in types..

This dynamic casting still has possibility to be realized, doesnt it ? or maybe I just have a wrong understanding...

Please give me your advice, Thanks in advance.

Best regards,
only4u
Something like
1
2
3
4
template <typename T>
void printPointerValue(void* p) {
	*((T *)p)
}
What's wrong with cout << p; where p is a void*?
<helios> Thank you for your advice. But I still need to enter the type because when we call the function we need to put the type as parameter of template. This condition is the same with static casting, not dynamically print the value regardless the type.

<jsmith> cout << p --> prints the address only... if we want to access the value at address that pointer points we have to use * in front of p. Because the type is void, the compiler says no. If we use visual basic, it has variable with "general type" you can print value of that variable.

Do you or anybody have advice or way to achieve this issue ?

Thank you in advance,
only4u

Do you realize there's no way to know at run time what a generic pointer is pointing to without adding data?
The only option I can see here is polymorphism, but that doesn't have the exact syntax you're looking for.
I am sorry, but I have put the chunk of code before at my beginning post (up there):

in main program:
int a = 999;
int b = "abcde"; --> i made a mistake here, it should be char* b = "abcde"
void* p;

p = &a; printPointerValue(p);
p = &b; printPointerValue(p);

void printPointerValue(void* p) {
}

p points to address of a... which actually similar to int* p = 999, but in above case we can print the value without static casting instead printing regardless the type of value that pointer points.

Thanks
only4u
So then what helios said.

1
2
3
4
template< typename T >
void printMe( const T* p ) {
    cout << p << ": " << *p << endl;
}


EDIT:

This will of course require T to be ostreamable.

To make type "Foo" ostreamable:

1
2
3
4
5
6
template< typename charT, typename Traits >
std::basic_ostream<charT, Traits>& operator<<(
  std::basic_ostream<charT, Traits>& os, const Foo& f )
{
    return os /* << f.field1, etc */;
}

Last edited on
Topic archived. No new replies allowed.