簡體   English   中英

在命令數據結構中使用並集

[英]Use of union in a command data structure

我正在做一個項目,我們在其中將命令從上層傳遞到下層。

1.一次處理單個命令

我們使用以下數據結構。

struct Command{
     //Different command types==> SEND / CREATE_TRANSACTION etc.
     CommandType type;

     //Associated parameters with every command
     union{
         struct{
             string remote_ip;
             uint16_t remote_port;
         }address;

         struct{
             string transaction_id;
             string transaction_details;
         }tsx;
         .
         .
         .
     }params;
};

我們為不同的命令傳遞不同的參數。 聯合使內存有效。

有沒有更好的方法(或設計模式)在C ++中做到這一點?

另一個。

2. 在一個命令對象中處理多個命令。

我可以這樣來做:

struct Command{
    uint64_t flag; //ORed value of different command types 

    //parameters
    struct{
        string remote_ip;
        uint16_t remote_port;
    }address;

    struct{
        string transaction_id;
        string transaction details;
    }tsx;
};

但是,它不是高效的內存。

有沒有更好的方法(在C ++中)在單個對象中創建多個命令?

您需要std::variantboost::variant 變體是區分類型安全的聯合。

struct address {
    string remote_ip;
    uint16_t remote_port;
};

struct tsx {
    string transaction_id;
    string transaction details;
};

using command = std::variant<address, tsx>;

用法示例:

command c0{tsx{/* ... */}};
std::visit(
    overload(
        [](const address&){ /* handle address case */ },
        [](const tsx&)    { /* handle tsx case */ }
    ),
    c0
);

為了了解如何實現overload和類似的模式匹配實用程序,請參閱我的ACCU 2017演講: “使用Lambda實現變體訪問”

您可以使用std :: variant和訪問者模式。 根據命令類型,訪問者對處理有效負載數據的反應會有所不同。

http://en.cppreference.com/w/cpp/utility/variant/visit

這提供了工會無法提供的類型安全性

使用聯合作為“變量”,尤其是為了“節省內存”,幾乎總是表明設計不佳。 您需要質疑設計/規格是否合理。 是的,還有更好的方法:

如果這兩個結構彼此無關,則將它們保留為2個單獨的結構(或類)。 設計沒有緊密耦合的程序比節省10-20字節的內存重要得多。

否則,如果這兩個結構確實具有某些共同點,則使“ params”成為包含該結構共同點的抽象基類。 然后讓“ address”和“ tsx”繼承該基類。

暫無
暫無

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

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