简体   繁体   English

直接使用嵌套结构成员

[英]Use a nested struct members directly

So I'm trying to nest a struct into another one by value, but I want to be able to import the members of the nested structs as if they are direct members of Generic struct.所以我试图按值将一个结构嵌套到另一个结构中,但我希望能够导入嵌套结构的成员,就好像它们是通用结构的直接成员一样。 There seems to be a using keywork in C++, but it doesn't work as I would have expected. C++ 中似乎有一个 using keywork,但它并没有像我预期的那样工作。

For example:例如:

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
}

This construct is made in this way to be able to create different user-extensible views into some differently-sized item buffer, where each item is a tagged union with custom contents and common header and footer.以这种方式构建此构造,以便能够将不同的用户可扩展视图创建到一些不同大小的项目缓冲区中,其中每个项目都是带有自定义内容和公共 header 和页脚的标记联合。

So the main question: How to import ("use") some struct into a different one and be able to access the nested struct' fields directly?所以主要问题是:如何将一些结构导入(“使用”)到另一个结构中并能够直接访问嵌套结构的字段?

There is a possible way to work around the problem by using inheritance, but it needs more structures:使用 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
};

Now you can use the B data as现在您可以将B数据用作

Data<B> data;

The header information will come first, the actual data follow. header 信息将首先出现,实际数据随后出现。 And the size will depend on the data structure.大小将取决于数据结构。

But please note that from a design point of view, this is highly dubious.但请注意,从设计的角度来看,这是非常可疑的。 I would prefer actual composition:我更喜欢实际的组成:

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

struct Data_A
{
    Header header;
    A data;
};

This allows you to read the header and data separately from the buffer.这允许您从缓冲区中单独读取 header 和数据。 It's also more explicit about the separation of the header and the data, and should make the code clearer and easier to read, understand and maintain. header 和数据的分离也更加明确,应该使代码更清晰,更易于阅读、理解和维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM