Pre-processor batch for all members of the structure

Is it possible to write a preprocessor macro that automatically iterates over all members of the structure?

I have a structure like this (automatically created from a Simulink model):

typedef struct {
  real_T driveStatusword;
  real_T posSensor[2];
  real_T softAbortDemand;
} ExtU_motionCtrlRTOS_T;

And similar:

struct CoreInputOffsets
{
    uint32_t driveStatusword;
    uint32_t posSensor;
    uint32_t softAbortDemand;
};

And I would like to do this operation:

void getCoreInputOffsets(CoreInputOffsets* pCoreInputOffsets)
{
    pCoreInputOffsets->driveStatusword = offsetof(ExtU_motionCtrlRTOS_T, driveStatusword);
    pCoreInputOffsets->posSensor = offsetof(ExtU_motionCtrlRTOS_T, posSensor);
    pCoreInputOffsets->softAbortDemand = offsetof(ExtU_motionCtrlRTOS_T, softAbortDemand);
}

But without the need to edit this function every time the structure changes, iterating over all members CoreInputOffsets.

+4
source share
2 answers

++ 14, , ( ) , . Antony Polukhin magic get library ( cppcon, , ). , ++ 11 ABI.

, ExtU_motionCtrlRTOS_T x;,

boost::pfr::flat_structure_tie(x) = boost::pfr::flat_structure_tie(some_unrelated_pod);

, . , , .


, , offsetof(), , ( , , ).

, , :

#include <boost/pfr/flat/core.hpp>

struct CoreInputOffsets
{
    uint32_t driveStatusword;
    uint32_t posSensor[2];
    uint32_t softAbortDemand;
};

template <typename T,std::size_t... Is>
void assignOffsets( CoreInputOffsets& offsets, std::index_sequence<Is...> )
{
  T t;
  (( boost::pfr::flat_get<Is>(offsets) = reinterpret_cast<char*>(&boost::pfr::flat_get<Is>(t)) - reinterpret_cast<char*>(&boost::pfr::flat_get<0>(t)) ), ...);
}

template <typename T>
void assignOffsets( CoreInputOffsets& offsets )
{
  assignOffsets<T>( offsets, std::make_index_sequence< boost::pfr::flat_tuple_size<T>::value >{} );
}

void getCoreInputOffsets(CoreInputOffsets* pCoreInputOffsets)
{
  assignOffsets<ExtU_motionCtrlRTOS_T>( *pCoreInputOffsets );
}

:

  • ++ 17 ( ++ 14)
  • , , ExtU_motionCtrlRTOS_T; , , , ,
  • , , undefined , .
  • CoreInputOffsets:: posSensor .
+3

"" , .

, , . , REFLECTABLE, .

, , , / , ?

+1

Source: https://habr.com/ru/post/1689250/


All Articles