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

如何实现不指定元素类型的C++容器工厂类?

解决方案

要实现你想要的工厂类,核心是利用C++的模板模板参数——因为你需要传入的是容器模板(比如std::vector)而非具体的容器类型(比如std::vector<int>)。

通用实现代码

#include <vector>
#include <list>

// 适配任意带类型参数的容器模板
template <template <typename...> typename t_container>
class factory {
public:
    // 模板别名:由用户指定元素类型及其他可选参数(如分配器)
    template <typename T, typename... Args>
    using container = t_container<T, Args...>;
};

使用示例

int main() {
    // 创建 std::vector<int>
    factory<std::vector>::container<int> my_vec;
    // 创建带自定义分配器的 std::vector<int>
    factory<std::vector>::container<int, std::allocator<int>> my_vec_with_alloc;
    // 创建 std::list<std::string>
    factory<std::list>::container<std::string> my_list;
}

原写法问题说明

你最初的代码用template <typename t_container>,要求传入的是具体类型(比如std::vector<int>),但你想传入的std::vector是容器模板而非类型,因此语法不合法。改用模板模板参数template <typename...> typename t_container后,就能接受std::vector这类模板作为参数,再通过内部的模板别名container让用户指定元素类型,最终生成具体的容器类型。

适配带非类型参数的容器(如std::array)

如果需要支持std::array这类带非类型模板参数的容器,可以专门定义适配类:

template <template <typename, size_t> typename t_container>
class array_factory {
public:
    template <typename T, size_t N>
    using container = t_container<T, N>;
};

// 使用方式
array_factory<std::array>::container<int, 5> my_array;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:03:10