簡體   English   中英

直接使用嵌套結構成員

[英]Use a nested struct members directly

所以我試圖按值將一個結構嵌套到另一個結構中,但我希望能夠導入嵌套結構的成員,就好像它們是通用結構的直接成員一樣。 C++ 中似乎有一個 using keywork,但它並沒有像我預期的那樣工作。

例如:

struct A
{
    int a;
    // some specific A stuff
};
struct B
{
    float a;
    // some specific B stuff
};

template<typename T>
struct Generic
{
    Kind kind; // an enum or an integer ID that allow to figure out what type is contained
    // some generic stuff

    // how to do this?
    using T t; // Error: a class-qualified name is required

    // some more generic stuff
};

void foo()
{
    Generic<B> g;
    g.t.a = 6.7 // we can do this with regular struct field
    g.a = 5.4; // but need to be able to do this
}

以這種方式構建此構造,以便能夠將不同的用戶可擴展視圖創建到一些不同大小的項目緩沖區中,其中每個項目都是帶有自定義內容和公共 header 和頁腳的標記聯合。

所以主要問題是:如何將一些結構導入(“使用”)到另一個結構中並能夠直接訪問嵌套結構的字段?

使用 inheritance 可以解決此問題,但它需要更多結構:

// The "data" structures
struct A { ... };
struct B { ... };

// Common "header" structure
struct Header { ... };

// The "generic" structure to combine the header with the data
template<typename D>
struct Data : Header, D
{
    // Empty
};

現在您可以將B數據用作

Data<B> data;

header 信息將首先出現,實際數據隨后出現。 大小將取決於數據結構。

但請注意,從設計的角度來看,這是非常可疑的。 我更喜歡實際的組成:

struct A
{
    // Actual A data fields follow
};

struct Data_A
{
    Header header;
    A data;
};

這允許您從緩沖區中單獨讀取 header 和數據。 header 和數據的分離也更加明確,應該使代碼更清晰,更易於閱讀、理解和維護。

暫無
暫無

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

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