【问题标题】:Initialize const parent struct member from derived struct从派生结构初始化 const 父结构成员
【发布时间】:2013-12-03 10:54:24
【问题描述】:

我正在编写一个结构层次结构,这些结构都派生自同一个基本结构。所述基本结构有一个标签字段,可以让我识别其中的内容。现在我想自动化该字段的初始化,因此没有错误,但不想为每个派生结构编写初始化程序。

我现在正在做的是使用中间代理结构来初始化基础结构。我的头文件的粗略版本是:

enum class Tag
{
    Header ,
    Entry  ,

    Unknown = ~0
};

struct Chunk
{
    const Tag tag ;

    Chunk( Tag t = Tag::Unknown ) : tag( t ) {}
};

template< Tag TAG > struct ChunkProxy : public Chunk
{
    ChunkProxy( void ) : Chunk( TAG ) {}
};

struct HeaderChunk : public ChunkProxy< Tag::Header >
{
    int whatever = 0 ;
};

struct EntryChunk : public ChunkProxy< Tag::Entry >
{
    int somedata = 0 ;
};

我觉得那里有那个块代理不太舒服,感觉可能有更好的方法来实现这一点;并且 chunk 本身不能是模板类,因为我无法通过指针传递它。

注意:我这样做是为了帮助我解析分块数据流,将从字符串读取的内存直接映射到 pod 结构。

编辑:根据 Archie 的回答,我向 Chunk 添加了一个构造函数,并从 ChunkProxy 构造函数中删除了 const_cast。

【问题讨论】:

    标签: c++ struct constants


    【解决方案1】:

    为什么不给Chunk添加一个构造函数?

    struct Chunk
    {
        const Tag tag;
    
        Chunk() : tag(Tag::Unknown) {}
        Chunk(Tag tag) : tag(tag) {}
    };
    
    template<Tag TAG> struct ChunkProxy : public Chunk
    {
        ChunkProxy(void) : Chunk(TAG) {}
    };
    

    实际上,使用此构造函数解决方案,您可以完全跳过ChunkProxy

    struct Chunk
    {
        const Tag tag;
    
        Chunk() : tag(Tag::Unknown) {}
        Chunk(Tag tag) : tag(tag) {}
    };
    
    struct HeaderChunk : public Chunk
    {
        int whatever = 0;
    
        HeaderChunk(void) : Chunk(Tag::Header) {}
    };
    
    struct EntryChunk : public Chunk
    {
        int whatever = 0;
    
        HeaderChunk(void) : Chunk(Tag::Entry) {}
    };
    

    【讨论】:

    • 实际情况要复杂一些。我特别想避免必须为每个子结构添加一个构造函数(它们有很多)。
    • @DiegoSánchez 如果你想避免这种情况,那么ChunkProxy(但有更好的名字,也许ChunkTraits?)是要走的路。只是不要这样做const_cast,因为这会引入 UB。
    • 关于 const_cast 的好点,匆忙添加它只是为了使示例编译。会改的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2016-02-18
    • 2015-02-19
    相关资源
    最近更新 更多