Replacing a void* in C++

Discussion in 'C++' started by Jim Langston, Sep 28, 2007.

  1. Jim Langston

    Jim Langston Guest

    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 T> class Message: public AIMsg
    {
    public:
    Message(): AIMsg( typeid(T).name() ) {}
    T Value;
    };

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

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

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

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

    return 0;
    }
    Jim Langston, Sep 28, 2007
    #1
    1. Advertising

  2. * Jim Langston:
    > 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 T> class Message: public AIMsg
    > {
    > public:
    > Message(): AIMsg( typeid(T).name() ) {}
    > T Value;
    > };
    >
    > void MessageHandler( AIMsg* Msg )
    > {
    > if ( Msg->MsgType == typeid(float).name() )
    > std::cout << dynamic_cast<Message<float>*>( Msg )->Value << "\n";
    > else if ( Msg->MsgType == typeid(int).name() )
    > std::cout << dynamic_cast<Message<int>*>( Msg )->Value << "\n";
    > }
    >
    > void MessageHandler2( AIMsg& Msg )
    > {
    > if ( Msg.MsgType == typeid(float).name() )
    > std::cout << dynamic_cast<Message<float>* >( &Msg )->Value << "\n";
    > if ( Msg.MsgType == typeid(int).name() )
    > std::cout << dynamic_cast<Message<int>* >( &Msg )->Value << "\n";
    > }
    >
    > int main()
    > {
    > Message<float> Bar;
    > Bar.Value = 54321.123f;
    > MessageHandler( &Bar );
    > MessageHandler2( Bar );
    >
    > Message<int> Bar2;
    > Bar2.Value = 123;
    > MessageHandler( &Bar2 );
    > MessageHandler2( Bar2 );
    >
    > return 0;
    > }


    Check out the visitor pattern.

    Cheers, & hth.,

    - Alf

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
    Alf P. Steinbach, Sep 28, 2007
    #2
    1. Advertising

  3. On Sep 28, 10:33 am, "Jim Langston" <> wrote:
    > 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<typename A, typename B> bool 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
    Chris ( Val ), Sep 28, 2007
    #3
  4. Jim Langston

    Jim Langston Guest

    "Chris ( Val )" <> wrote in message
    news:...
    > On Sep 28, 10:33 am, "Jim Langston" <> wrote:
    >> 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<typename A, typename B> bool 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 MinerGlobalState::OnMessage(Miner* 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_cast<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_cast.

    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 MinerGlobalState::OnMessage(Miner* pMiner, const Telegram& msg, const
    float& ExtraInfo)

    A different class may have it declared:

    bool CookStew::OnMessage(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_cast and am trying to
    stick any such ugliness away from the onmessage methods.
    Jim Langston, Sep 28, 2007
    #4
  5. * 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_cast and am trying to
    > stick any such ugliness away from the onmessage methods.



    Check out the visitor pattern.

    Cheers, & hth.,

    - Alf

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
    Alf P. Steinbach, Sep 28, 2007
    #5
  6. Jim Langston

    Jim Langston Guest

    "Alf P. Steinbach" <> wrote in message
    news:...
    >* 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_cast 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.
    Jim Langston, Sep 28, 2007
    #6
  7. * Jim Langston:
    > "Alf P. Steinbach" <> wrote in message
    > news:...
    >> * 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_cast 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.


    OK.

    Let's first dispense with the strings in your code, because /that's not
    guaranteed to work/. Or more precisely, I'd have to scrutinize the
    standard to find a statement guaranteeing uniqueness of
    typeid(T).name(), and I don't think there is such a statement. So,
    first take, in the Process Of Transforming Jim's Code:


    <code>
    #include <iostream>
    #include <ostream>
    #include <typeinfo>
    #include <string>

    struct AIMsg
    {
    public:
    AIMsg() {}
    virtual std::type_info const& valueType() const = 0;
    virtual ~AIMsg() {}
    };

    template <class T> class Message: public AIMsg
    {
    public:
    Message() {}
    virtual std::type_info const& valueType() const
    {
    return typeid( T );
    }
    T value;
    };

    void messageHandler( AIMsg const& msg )
    {
    if ( msg.valueType() == typeid(float) )
    {
    std::cout
    << dynamic_cast<Message<float> const*>( &msg )->value
    << "\n";
    }
    if ( msg.valueType() == typeid(int) )
    {
    std::cout
    << dynamic_cast<Message<int> const*>( &msg )->value
    << "\n";
    }
    }

    int main()
    {
    Message<float> Bar;
    Bar.value = 54321.123f;
    messageHandler( Bar );

    Message<int> Bar2;
    Bar2.value = 123;
    messageHandler( Bar2 );
    }
    </code>


    Next, we recall that in C++, explicit discrimination on type is usually
    best replaced with use of a virtual function. In the derived class
    where the implementation of that virtual function is executed, the exact
    derived type is known. So then it can call a templated handler, take 2:


    <code>
    #include <iostream>
    #include <ostream>
    #include <typeinfo>
    #include <string>

    struct AIMsg
    {
    public:
    AIMsg() {}
    virtual std::type_info const& valueType() const = 0;
    virtual void callHandler() const = 0;
    virtual ~AIMsg() {}
    };

    template <class T> class Message;
    template< typename T > void handle( Message<T> const& );

    template <class T> class Message: public AIMsg
    {
    public:
    Message() {}
    virtual std::type_info const& valueType() const
    {
    return typeid( T );
    }
    virtual void callHandler() const
    {
    handle( *this );
    }
    T value;
    };

    template< typename T >
    void handle( Message<T> const& msg )
    {
    std::cout << msg.value << "\n";
    }

    int main()
    {
    Message<float> Bar;
    Bar.value = 54321.123f;
    Bar.callHandler();

    Message<int> Bar2;
    Bar2.value = 123;
    Bar2.callHandler();
    }
    </code>


    I don't know whether you need the type-info name for something (like
    e.g. tracing or logging) so I left it in, but note that at least in the
    code above it's no longer used, and could just be removed.

    To make this a full-fledged visitor pattern you'd have to pass an object
    to callHandler(), and let that object provide a templatized handle()
    member function. But that's just needless complication for the task
    above. You can regard the above as a special case visitor pattern.


    Cheers, & hth.,

    - Alf

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
    Alf P. Steinbach, Sep 28, 2007
    #7
  8. On Sep 29, 5:11 am, "Jim Langston" <> wrote:
    > "Chris ( Val )" <> wrote in messagenews:...
    >
    >
    >
    >
    >
    > > On Sep 28, 10:33 am, "Jim Langston" <> wrote:
    > >> 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<typename A, typename B> bool 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 MinerGlobalState::OnMessage(Miner* 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_cast<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_cast.


    [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::stringstream 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
    Chris ( Val ), Sep 29, 2007
    #8
  9. * Chris ( Val ), referring to else-thread:
    >
    > That visitor pattern looks different to ones
    > that I've seen in the past :)


    Yes. To see it as a visitor pattern (which is important in order to
    maintain the code, in particular to extend it) you have to understand
    the essence instead of focusing on superficial outer dressing. I.e.,
    understand why the electrician does something instead of blindly copying
    what she does, which is likely to result in a nasty shock.


    > It is just a simple function acting polymorphically.


    Yes.

    Cheers, & hth.,

    - Alf

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
    Alf P. Steinbach, Sep 29, 2007
    #9
  10. On Sep 30, 4:12 am, "Alf P. Steinbach" <> wrote:
    > * Chris ( Val ), referring to else-thread:
    >
    >
    >
    > > That visitor pattern looks different to ones
    > > that I've seen in the past :)

    >
    > Yes. To see it as a visitor pattern (which is important in order to
    > maintain the code, in particular to extend it) you have to understand
    > the essence instead of focusing on superficial outer dressing. I.e.,
    > understand why the electrician does something instead of blindly copying
    > what she does, which is likely to result in a nasty shock.


    [snip]

    Yes, I agree.

    I was just pointing out that the visitor pattern (at least
    from what I have read in the GOF book), is much more complex
    in its nature than what you described as having the same name.

    Cheers,
    Chris Val
    Chris ( Val ), Sep 30, 2007
    #10
  11. Jim Langston

    rolkA Guest

    On 28 sep, 21:11, "Jim Langston" <> wrote:
    >
    > 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_cast<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_cast.


    Btw, with void* you dont have to use reinterpret_cast. 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 ^_^
    rolkA, Sep 30, 2007
    #11
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ollej Reemt
    Replies:
    7
    Views:
    494
    Jack Klein
    Apr 22, 2005
  2. Stig Brautaset

    `void **' revisited: void *pop(void **root)

    Stig Brautaset, Oct 25, 2003, in forum: C Programming
    Replies:
    15
    Views:
    767
    The Real OS/2 Guy
    Oct 28, 2003
  3. Replies:
    5
    Views:
    806
    S.Tobias
    Jul 22, 2005
  4. Replies:
    1
    Views:
    382
    Victor Bazarov
    May 23, 2007
  5. Rob Meade

    Replacing - and not Replacing...

    Rob Meade, Apr 5, 2005, in forum: ASP General
    Replies:
    5
    Views:
    251
    Chris Hohmann
    Apr 11, 2005
Loading...

Share This Page