473,938 Members | 1,626 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Replacing a void* in C++

I am using some code that I got that uses a form a message dispatching where
the data is passed via a void*. I don't like void*'s so am experimenting
with a different way to do them in C++. I don't use boost, and this is what
I've come up with so far, but it seems fairly ugly.

In actual use the final handler that handles the data would know what type
the data should be based on other paramaters in the function call, so this
is just proof of concept.

Has anyone a better idea? I tend to like MessageHandler2 using a reference
instead of a pointer.

#include <iostream>
#include <string>

struct AIMsg
{
public:
AIMsg( const std::string& MsgType ): MsgType( MsgType ) {}
std::string MsgType;
virtual ~AIMsg() {}
};

template <class Tclass Message: public AIMsg
{
public:
Message(): AIMsg( typeid(T).name( ) ) {}
T Value;
};

void MessageHandler( AIMsg* Msg )
{
if ( Msg->MsgType == typeid(float).n ame() )
std::cout << dynamic_cast<Me ssage<float>*>( Msg )->Value << "\n";
else if ( Msg->MsgType == typeid(int).nam e() )
std::cout << dynamic_cast<Me ssage<int>*>( Msg )->Value << "\n";
}

void MessageHandler2 ( AIMsg& Msg )
{
if ( Msg.MsgType == typeid(float).n ame() )
std::cout << dynamic_cast<Me ssage<float>* >( &Msg )->Value << "\n";
if ( Msg.MsgType == typeid(int).nam e() )
std::cout << dynamic_cast<Me ssage<int>* >( &Msg )->Value << "\n";
}

int main()
{
Message<floatBa r;
Bar.Value = 54321.123f;
MessageHandler( &Bar );
MessageHandler2 ( Bar );

Message<intBar2 ;
Bar2.Value = 123;
MessageHandler( &Bar2 );
MessageHandler2 ( Bar2 );

return 0;
}
Sep 28 '07 #1
5 1740
On Sep 28, 10:33 am, "Jim Langston" <tazmas...@rock etmail.comwrote :
I am using some code that I got that uses a form a message dispatching where
the data is passed via a void*. I don't like void*'s so am experimenting
with a different way to do them in C++. I don't use boost, and this is what
I've come up with so far, but it seems fairly ugly.

In actual use the final handler that handles the data would know what type
the data should be based on other paramaters in the function call, so this
is just proof of concept.

Has anyone a better idea? I tend to like MessageHandler2 using a reference
instead of a pointer.
I don't completely understand why you require 2 classes, but you
could look into template specialisation to see if that helps you.

I just wanted to make the point that unless it has changed in the
recent standard, relying on an accurate string from the 'typeid'
"name()" member is not reliable, and implementation dependant; if
a string is returned at all.

Additionally, I don't think it is being used effectively the way
you have it.

For example, the construct "typeid( float ).name()" will always
produce the same hard coded result on one side of the evaluation,
provided a valid result is available for evaluation.

Much better to use something like the following, so you're
not bound to that hard coded construct:

template<typena me A, typename Bbool isEqual( A a, B b ) {
return typeid( a ) == typeid( b );
}

int main()
{
char A(0);
int B(0);
long C(0);

std::cout << std::boolalpha << isEqual( A, A ) << '\n';
std::cout << std::boolalpha << isEqual( A, B ) << '\n';
std::cout << std::boolalpha << isEqual( A, C ) << '\n';

return 0;
}

-- OUTPUT --
true
false
false

Cheers,
Chris Val

Sep 28 '07 #2
"Chris ( Val )" <ch******@gmail .comwrote in message
news:11******** **************@ 22g2000hsm.goog legroups.com...
On Sep 28, 10:33 am, "Jim Langston" <tazmas...@rock etmail.comwrote :
>I am using some code that I got that uses a form a message dispatching
where
the data is passed via a void*. I don't like void*'s so am experimenting
with a different way to do them in C++. I don't use boost, and this is
what
I've come up with so far, but it seems fairly ugly.

In actual use the final handler that handles the data would know what
type
the data should be based on other paramaters in the function call, so
this
is just proof of concept.

Has anyone a better idea? I tend to like MessageHandler2 using a
reference
instead of a pointer.

I don't completely understand why you require 2 classes, but you
could look into template specialisation to see if that helps you.

I just wanted to make the point that unless it has changed in the
recent standard, relying on an accurate string from the 'typeid'
"name()" member is not reliable, and implementation dependant; if
a string is returned at all.

Additionally, I don't think it is being used effectively the way
you have it.

For example, the construct "typeid( float ).name()" will always
produce the same hard coded result on one side of the evaluation,
provided a valid result is available for evaluation.

Much better to use something like the following, so you're
not bound to that hard coded construct:

template<typena me A, typename Bbool isEqual( A a, B b ) {
return typeid( a ) == typeid( b );
}

int main()
{
char A(0);
int B(0);
long C(0);

std::cout << std::boolalpha << isEqual( A, A ) << '\n';
std::cout << std::boolalpha << isEqual( A, B ) << '\n';
std::cout << std::boolalpha << isEqual( A, C ) << '\n';

return 0;
}

-- OUTPUT --
true
false
false
I would rather not hard code any types at all. I'm working with existing
code that recieves messages such as:

bool MinerGlobalStat e::OnMessage(Mi ner* pMiner, const Telegram& msg)

With Telegram defined as:
struct Telegram
{
int Sender;
int Receiver;
int Msg;
double DispatchTime;
void* ExtraInfo;
// constructor etc...
}

It is the void* ExtraInfo I am trying to make a little more friendly. In the
OnMessage I have to do things such as:
int Amount = *reinterpret_ca st<int*>( msg.ExtraInfo );

Which, okay, usually, is okay. But, somewhere someone may have stuck an int
in there instead of a float or such. Not very typesafe. And I don't like
the reinterpret_cas t.

What would be ideal would be to move the ExtraInfo out of Telegram and make
it a paramater in OnMessage changing the signature to:
bool MinerGlobalStat e::OnMessage(Mi ner* pMiner, const Telegram& msg, const
float& ExtraInfo)

A different class may have it declared:

bool CookStew::OnMes sage(MinersWife * wife, const Telegram& msg, const
SomeClass& ExtraInfo)

or such.

The existing code I'm working with has many source files and I don't really
want to have to redesign the whole class heirarchy to use the visitor
pattern, and also there may be a case where one message handler may need to
have the ExtraInfo as different typed depending on the Msg paramater of the
Telegram.

I know that void*'s were used a lot in C callbacks and had hoped that by now
someone had a good way to deal with them in C++. Upcasting doesn't seem to
be working. Trying to upcast an AIMsg* to a Message<float>* didn't work and
got me nowhere.

Trying to google for "change void* in C++" doesn't help has void is found
too many places in function/method returns. It looks like somewhere I'm
going to have to do a dymaic_cast or a reinterpret_cas t and am trying to
stick any such ugliness away from the onmessage methods.


Sep 28 '07 #3
"Alf P. Steinbach" <al***@start.no wrote in message
news:13******** *****@corp.supe rnews.com...
>* Jim Langston:
>>
Trying to google for "change void* in C++" doesn't help has void is found
too many places in function/method returns. It looks like somewhere I'm
going to have to do a dymaic_cast or a reinterpret_cas t and am trying to
stick any such ugliness away from the onmessage methods.


Check out the visitor pattern.
I've been reading up on the visitor pattern, and if I was to develop this
class heirarchy from scratch, I'd probalby use that. However, I don't see
how using the visitor pattern helps with converting a void * in an existing
class heirarchy. Unless I'm missing something or my googles for "visitor
pattern c++" are not showing a specific usage for this case.
Sep 28 '07 #4
On Sep 29, 5:11 am, "Jim Langston" <tazmas...@rock etmail.comwrote :
"Chris ( Val )" <chris...@gmail .comwrote in messagenews:11* *************** ******@22g2000h sm.googlegroups .com...


On Sep 28, 10:33 am, "Jim Langston" <tazmas...@rock etmail.comwrote :
I am using some code that I got that uses a form a message dispatching
where
the data is passed via a void*. I don't like void*'s so am experimenting
with a different way to do them in C++. I don't use boost, and this is
what
I've come up with so far, but it seems fairly ugly.
In actual use the final handler that handles the data would know what
type
the data should be based on other paramaters in the function call, so
this
is just proof of concept.
Has anyone a better idea? I tend to like MessageHandler2 using a
reference
instead of a pointer.
I don't completely understand why you require 2 classes, but you
could look into template specialisation to see if that helps you.
I just wanted to make the point that unless it has changed in the
recent standard, relying on an accurate string from the 'typeid'
"name()" member is not reliable, and implementation dependant; if
a string is returned at all.
Additionally, I don't think it is being used effectively the way
you have it.
For example, the construct "typeid( float ).name()" will always
produce the same hard coded result on one side of the evaluation,
provided a valid result is available for evaluation.
Much better to use something like the following, so you're
not bound to that hard coded construct:
template<typena me A, typename Bbool isEqual( A a, B b ) {
return typeid( a ) == typeid( b );
}
int main()
{
char A(0);
int B(0);
long C(0);
std::cout << std::boolalpha << isEqual( A, A ) << '\n';
std::cout << std::boolalpha << isEqual( A, B ) << '\n';
std::cout << std::boolalpha << isEqual( A, C ) << '\n';
return 0;
}
-- OUTPUT --
true
false
false

I would rather not hard code any types at all. I'm working with existing
code that recieves messages such as:

bool MinerGlobalStat e::OnMessage(Mi ner* pMiner, const Telegram& msg)

With Telegram defined as:
struct Telegram
{
int Sender;
int Receiver;
int Msg;
double DispatchTime;
void* ExtraInfo;
// constructor etc...

}

It is the void* ExtraInfo I am trying to make a little more friendly. In the
OnMessage I have to do things such as:
int Amount = *reinterpret_ca st<int*>( msg.ExtraInfo );

Which, okay, usually, is okay. But, somewhere someone may have stuck an int
in there instead of a float or such. Not very typesafe. And I don't like
the reinterpret_cas t.
[snip]

What are the data types are you only interested
in accepting?

When you say "instead of a float", does that mean
you require floats and floates only? or are doubles
legal according to your spec as well?

The reason I ask, is because I think your biggest
problem happens well before the OnMessage member
function.

Personally, I would stop the client entering the
wrong data type to begin with, and set up a
constraint to dissallow the wrong types to be
entered from the word go.

You could use teamplates and function overloading
to do this. Or even capture the data into a
std::stringstre am object and sort it out from
there.

[snip]
The existing code I'm working with has many source files and I don't really
want to have to redesign the whole class heirarchy to use the visitor
pattern, and also there may be a case where one message handler may need to
have the ExtraInfo as different typed depending on the Msg paramater of the
Telegram.
That visitor pattern looks different to ones
that I've seen in the past :-)

It is just a simple function acting polymorphically .

--
Chris Val

Sep 29 '07 #5
On 28 sep, 21:11, "Jim Langston" <tazmas...@rock etmail.comwrote :
>
It is the void* ExtraInfo I am trying to make a little more friendly. In the
OnMessage I have to do things such as:
int Amount = *reinterpret_ca st<int*>( msg.ExtraInfo );

Which, okay, usually, is okay. But, somewhere someone may have stuck an int
in there instead of a float or such. Not very typesafe. And I don't like
the reinterpret_cas t.
Btw, with void* you dont have to use reinterpret_cas t. void* can be
casted to any pointer and any pointer can be casted to void*, with
static_cast. It's not THAT bad, I'm still using this for old-school
callbacks ("userdata") . What is VERY bad is to reinterpret POD (with a
pointer and a size).
Though it doesn't solve your problem, sorry ^_^

Sep 30 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
1881
by: Jay Nabonne | last post by:
Hi, This might sound odd, but we want to replace the allocation scheme used by new and delete without changing operator new and operator delete. (The global operators are shared and we can't change them.) We can replace operator new functionality by providing additional parameters to the new function call (ala Stroustrup): class foo_t;
8
5059
by: Jo Segers | last post by:
Hi, How can I restrict the keyboard input in a textBox to 0..9? In the keydown event KeyValue is get only. Where can I alter the keyboard input? Mvg,
7
2615
by: Ryan Taylor | last post by:
Hi. I have some code that dynamically generates a PDF and spits this content directly to the web browser. I use HTMLDoc to create the Pdf's from html. So the user can click on a button "Print PDF" and the current page magically becomes a PDF file. This worked great until we moved the site to https. Now, when the button is clicked, I get a warning that This page contains both secure and nonsecure items. Do you want to display the...
3
3925
by: jens.buchta | last post by:
Hi! I'm using a DataGrid with a template column to display an Image inside of it. I'm hooking into its OnPrerender-Event to set the ImageURL-Property dynamically. Everything works just fine here, until I thought "It would be cool, if the user could click on that image..". So I replaced the Image-Control with an ImageButton. My Problem is, that the ImageButton doesn't fire any events. Any other
2
2337
by: Mark P | last post by:
Consider a class in which I redefine operator new(std::size_t): struct A { void* operator new(std::size_t size) {/* my implementation */} }; This has the consequence of hiding the placement version of operator new: void* operator new(std::size_t size, void* location);
11
3078
by: 05l8kr | last post by:
Struggling greatly here with C++ but I find it interesting at the same time. Any good books to buy or web sites to help with this program? For the following - I'm suppose to replace the first three statements with cin and cout statements so that the values for the age, salary, and distance_to_the_moon can be obtained from the user. This make the program flexible so that everytime is is run different numbers are used. # comments...
32
3929
by: FireHead | last post by:
Hello C World & Fanatics I am trying replace fgets and provide a equavivalant function of BufferedInputReader::readLine. I am calling this readLine function as get_Stream. In the line 4 where default_buffer_length is changed from 4 --24 code works fine. But on the same line if I change the value of default_buffer_length from 4 --10 and I get a memory error. And if the change the value of the same variable from 4 --1024 bytes;
5
3827
by: RS24 | last post by:
Hi! Can someone tell me the correct answer for these ... Replace the following code using new operator- (Assume int is 2 bytes) #define MAXROW 3 #define MAXCOL 4 1.) void main()
1
4517
by: patelgaurav85 | last post by:
Hi, I want to convert xml in one format into another xml format shown below Input xml : <Name> <Name1> <Name11>Name11</Name11> <Name12>Name12</Name12>
0
10133
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11522
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
11287
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10655
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9854
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8216
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7380
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6073
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6292
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.