You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Thing2Container模板容器简化Thing2数组实例化?

实现自动绑定Thing1引用的Thing2Container模板容器

现有代码中,Thing2的构造必须传入Thing1的引用,当前需要手动逐个构造std::array<Thing2, count>的每个元素并绑定对应的Thing1实例。我们需要实现一个模板类Thing2Container,通过Thing2Container<count> thing2_pool(thing1_pool);的方式,内部自动完成std::array<Thing2, count>的初始化,每个Thing2对象对应绑定thing1_pool中同索引的Thing1引用。

完整实现代码

#include <array>
#include <cstddef>
#include <utility> // 用于std::index_sequence

class Thing1
{
public:
    Thing1() noexcept                    = default;
    Thing1(Thing1 const&)                = delete;
    Thing1(Thing1&&) noexcept            = delete;
    Thing1& operator=(Thing1 const&)     = delete;
    Thing1& operator=(Thing1&&) noexcept = delete;
};

class Thing2
{
public:
    explicit Thing2(Thing1& t1) noexcept: thing1(t1) {}

    Thing2() noexcept                    = delete;
    Thing2(Thing2 const&)                = delete;
    Thing2(Thing2&&) noexcept            = delete;
    Thing2& operator=(Thing2 const&)     = delete;
    Thing2& operator=(Thing2&&) noexcept = delete;

    Thing1& get_thing1() { return this->thing1; }

private:
    Thing1& thing1;
};

// 实现Thing2Container模板
template<std::size_t Count>
class Thing2Container
{
public:
    // 对外暴露的构造函数:接收Thing1的array
    explicit Thing2Container(std::array<Thing1, Count>& thing1_pool)
        : Thing2Container(thing1_pool, std::make_index_sequence<Count>{})
    {}

    // 提供和std::array一致的访问接口
    Thing2& operator[](std::size_t idx) noexcept { return thing2_array[idx]; }
    const Thing2& operator[](std::size_t idx) const noexcept { return thing2_array[idx]; }

    std::array<Thing2, Count>& data() noexcept { return thing2_array; }
    const std::array<Thing2, Count>& data() const noexcept { return thing2_array; }

private:
    // 辅助构造函数:利用编译期索引序列完成初始化
    template<std::size_t... Idx>
    Thing2Container(std::array<Thing1, Count>& thing1_pool, std::index_sequence<Idx...>)
        : thing2_array{ Thing2(thing1_pool[Idx])... }
    {}

    std::array<Thing2, Count> thing2_array;
};

static constexpr size_t count = 4u;

std::array<Thing1, count> thing1_pool;
// 自动完成所有Thing2的构造与绑定
Thing2Container<count> thing2_pool(thing1_pool);

int main()
{
    // 验证绑定正确性(可选)
    for (std::size_t i = 0; i < count; ++i) {
        // assert(&thing2_pool[i].get_thing1() == &thing1_pool[i]);
    }
    return 0;
}

核心实现说明

  • 编译期索引序列:借助std::index_sequence和std::make_index_sequence生成0到Count-1的编译期索引,避免运行时循环,保证初始化效率。
  • 参数包展开:辅助构造函数通过模板参数包Idx...展开索引,逐个构造Thing2对象并初始化内部的std::array,实现自动绑定对应索引的Thing1引用。
  • 访问兼容性:提供operator[]和data()方法,让外部可以像使用普通std::array一样操作Thing2Container内部的元素,保持接口一致性。

内容的提问来源于stack exchange,提问作者natersoz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 12:50:17