Re: Generic message holder class design
Mark <ma740988@gmail.com> writes:
<snip />
int main()
{
typedef std::vector < Msg_Holder* > MSG_HOLDER_VEC ;
MSG_HOLDER_VEC msg_vec;
msg_vec.push_back ( new Msg_Holder < R1_Msg > (
( 1, singleton < R1_Msg >::instance() ) ) ) ;
std::cin.get();
}
Of course, there is an error here that illustrates, I believe, one of
the problems that you are facing, as I am sure that you are aware.
Msg_Holder is a templated class, and so for the above to work you would
need to use something like:
typedef std::vector< Msg_Holder<R1_Msg> *> MSG_HOLDER_VEC;
which would then commit you to only adding R1_Msg's to the vector. One
way of addressing this, as I suggest below, might be to use something
like boost::any.
I'd like store an instance of each message within a container of
Msg_Hholder type. My issues here is predicated upon template usage/
understanding (something i struggle with often), noetheless at issue:
a) The Msg_Holder class is a generic class and I'm unsure how to
typedef the vector so I could push-back message classes
How about something like the following, which implemented as here also
handles your wish for chaining:
// add
#include <boost/any.hpp>
class message_holder_vec {
public:
std::vector<boost::any>& push_back(boost::any mh) {
msg_vec_.push_back(mh);
return msg_vec_;
}
/**
* other important vector-like methods, such as begin(), end()
* rbegin(), rend(), etc.
*/
private:
std::vector<boost::any> msg_vec_;
};
int main()
{
message_holder_vec msg_vec;
msg_vec
.push_back(boost::any(new Msg_Holder<R1_Msg>(1, singleton<R1_Msg>::instance())))
.push_back(boost::any(new Msg_Holder<R2_Msg>(1, singleton<R2_Msg>::instance())));
// ...
}
b) How do I enforce the use of the singleton in the Msg_Holder
constructor? IOW: push_back of Msg_Holder instances must be routed
through the singleton class.
c) I suspect there's no way to 'chain' push back? Ideally I'd like to
do .
msg_vec.push_back ( id1, single_instance::r1_msg ).
push_back ( id2, single_instance::r2_msg ) // etc.;
See previous, which illustrates how chaining is possible, though I
haven't pursued all the simplifications that, as you say, you would
ideally like.
lots more
// later iterate and find the id i'm interested in)
R1_Msg obj ;
for ( MSG_HOLDER_VEC::const_iterator it = msg_vec.begin(), it !=
msg_ve.end(); ++it ) {
if ( .. ... ) {
obj = it -> ....
//increment the count
int ->
}
}
Implementing some form of iterator traits for the message_holder_vec
class above could be the solution here, together with the appropriate
methods required to usefully wrap the underlying vector.
Of course this might seem painful but I dont think a map helps me
here.
I'm open to ideas (source snippet works even better). Thanks in
advance.
Mark
Just some thoughts.
Regards
Paul Bibbings
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]