簡體   English   中英

宏或 c++ 模板更改 struct 或 class 中的 const 變量值

[英]Macro or c++ template to change const variable value in struct or class

我正在 C++ 中實現一個協議,這是一個正在進行的項目,因此協議經常更改,我必須相應地更改代碼。

假設我定義一條消息如下:

struct Message {
  const int MSG_LENGTH = 3; // sizeof(a) + sizeof(b)
  uint8_t a;
  uint16_t b;
};

現在我想在Message中添加一個新字段uint32_t c ,但我不想手動更改MSG_LENGTH

是否可以使用一些技巧(宏或模板)來實現這一點?

謝謝。

一種想法可能是以std::tuple的形式定義消息:

#include <cstddef>
#include <cstdint>
#include <iostream>
#include <tuple>

template<class... Types>
struct MessageBase : std::tuple<Types...> {
    static constexpr size_t MSG_LENGTH() {
        return (sizeof(Types) + ...);       // calc the size of the fields
    }
};

struct Message : MessageBase<uint8_t, uint16_t> {};

int main() {
    constexpr auto x = Message::MSG_LENGTH();

    std::cout << x << '\n'; //  prints 3
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM