Can I loop through (public) attributes of a C++ cl

2019-02-26 06:04发布

I found the answer for both C Structs and C# classes but came back empty-handed concerning C++. EDIT : In C, you can't. In C# it's the GetProperties() method.

The context: I have a C++ class with public attributes (let's say a Point with X, Y, Z). I want to send these attributes via UDP to a Java client. My idea was to create a byte (char *) buffer with the three attributes (i took care of the endianness problems).

prepareForUdp(char * buffer)
 {
   int offset = 0;
   int offsetValue = 4;
   char tempBuffer[16];  

   memcpy( tempBuffer, &X_, sizeof(X_) );
   offset = offset + offsetValue;
   memcpy( tempBuffer + offset, &Y_, sizeof(Y_) );
   offset = offset + offsetValue;
   memcpy( tempBuffer + offset, &Z_, sizeof(Z_) );
   offset = offset + offsetValue;  

   memcpy( buffer, tempBuffer, sizeof(buffer) );
 }

I want my interface to be evolutive, because the point may get a fourth, a five, or an n-th dimension, and I want my prepareForUdp() method to be (relatively) generic.

My question is : how do I loop (or iterate) through my attributes ?

2条回答
男人必须洒脱
2楼-- · 2019-02-26 06:41

There is no reflection in C++. So, the answer is, you can't :)

查看更多
闹够了就滚
3楼-- · 2019-02-26 06:50

Here's an article on reflection and how to deal with the fact that c++ doesn't do it.

查看更多
登录 后发表回答