[英]accessing data members of nested struct and passing struct to function C++
[英]C++ passing a struct to a function to access a nested struct
我有一些以嵌套結構組織的數據,並且正在嘗試訪問它。 有 4 層,那么最終的結構體總是有 2 個變量; val
和addr
:
struct Flash{
struct Settings{
struct UnderVoltage{
struct Threshold{
int16_t val = 2850;
uint16_t addr = 0x4481;
} Threshold;
struct Delay{
uint8_t val = 2;
uint16_t addr = 0x4483;
} Delay;
struct Recovery{
int16_t val = 2900;
uint16_t addr = 0x4484;
} Recovery;
} UnderVoltage;
} Settings;
} Flash;
我希望能夠有一個功能
void writeThreshold(){
writeFlash( Flash.Settings.UnderVoltage.Threshold );
}
然后調用一個函數
void writeFlash( struct dataParam ){
byte addr1 = dataParam.addr & 0xFF;
byte addr2 = ( dataParam.addr >> 8 ) & 0xFF;
uint8_t byteLen = sizeof( dataParam.val );
byte valBytes[ byteLen ];
for( int i = 0; i < byteLen; i++ ){
valBytes[ i ] = dataParam.val >> ( i * 8 );
}
}
那么有沒有辦法將結構嵌套發送到函數,以便函數可以訪問其中的變量?
謝謝
您可以使用函數模板:
template<typename T>
void writeFlash(const T& dataParam){
// ... as before
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.