Hi,
I am coding a c++ based simulator, for which i need to implement a message queue.

The structure of the problem is such.

We have a program that contain a "queue" of messagePacket
messagePacket in this case is a pair <int , message> where message is a structure struct message The structure of a message is

struct message
{
int id;
int sender;
int recver;
dataPacket data;
};

for generic programming, i want to allow the user to define the DATATYPE of data (dataPacket) generically,

So I wrote

template <class dataObject> 
class dataPacket
{
      dataObject data;
      public:
             dataPacket(dataObject inData)
             {
                    data = inData;                
             }
      
};

The intention is, that depending on my/users requirement, he can design a dataPacket as say

struct newdata
{
vector <int> array;
};


dataPacket <newdata> myData;

message.data = myData

The problem might be visible that without a definite dataype definition in the definition of message, I cannot define the structure message.

I would like to know if it is possible to have dataPacket <void> data; in the definition of message structure.

Thanking you in advance,

Regards
Ruturaj

This is the complete code for your reference, which fails.

/*
This is the class that creates he data-Type of each packet
*/

template <class dataObject> 
class dataPacket
{
      dataObject data;
      public:
             dataPacket(dataObject inData)
             {
                    data = inData;                
             }
      
};


/*
This is a message
*/
struct message
{
       int messageId;
       int senderId;
       int recvId;
       dataPacket <SOMETHING GENERIC HERE> data;
};

typedef pair<int , message> simMessage;


/*
This class is the major message passing Queue that will be executed at evey step
*/
class messageQ
{

      
       class order
       {
         public:
           bool operator() (const simMessage& lhs, const simMessage& rhs) const
           {
               return (lhs.first>rhs.first);
           }
       };
       
       typedef priority_queue < simMessage , vector < simMessage >, order > MPQ;
       
       MPQ Queue;  
       
       public:
};

Thanking you,
Regards
Ruturaj

The obvious (to me anyway) way round this is to create a
base class to either message or to dataPacket.
e.g.

struct baseMessage
{
  int messageId;
  int senderId;
  int recvId;
};

template<typename TX>
struct message : public baseMessage
{
  dataPacket<TX> data;
};

Then store a pointer to the base-class and get everything by
virtual functions / dynamic_cast etc.

If you intend to do this, have a look at the boost::any class as it effectively does that for you without having to write any code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.