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

如何将针对不同std容器的函数模板合并为一个并保留参数类型关联

合并std::list和std::forward_list的函数模板解决方案

通用容器模板方案

最直接的方式是将函数模板的参数改为通用容器类型,通过容器的value_type成员提取元素类型,从而保持内部std::vector<T>与传入参数的类型关联。这种方案兼容所有符合标准容器接口的类型(包括std::list和std::forward_list)。

完整代码示例

#include <iostream>
#include <list>
#include <forward_list>
#include <vector>

template <typename Container>
void prinList(Container list) {
    for (auto var : list) { std::cout << var << " "; }
    std::cout << '\n';

    // 通过容器的value_type获取元素类型,保持与参数的类型关联
    using T = typename Container::value_type;
    std::vector<T> vec;
    auto it1 = list.begin();
    auto it2 = list.end();
    vec.assign(it1, it2);
}

int main(){
    std::forward_list<int> F_list1={1,2,3,4,5};
    prinList(F_list1);

    std::list<int> list1={10,11,12,13};
    prinList(list1);

    return 0;
}

说明

  • 模板参数Container接受任意符合标准容器接口的类型,范围for循环、begin()/end()调用都是标准容器的通用操作,因此无需针对std::list或std::forward_list单独实现。
  • typename Container::value_type用于获取容器内部元素的类型T,确保std::vector<T>与传入容器的元素类型完全一致,保持了类型关联。

限制仅支持list和forward_list的方案(C++20+)

如果需要严格限制函数只能接受std::list和std::forward_list,可以使用C++20引入的concept特性来约束模板参数。

完整代码示例

#include <iostream>
#include <list>
#include <forward_list>
#include <vector>
#include <concepts>
#include <type_traits>

// 定义约束规则:仅允许std::list或std::forward_list
template <typename Container>
concept ListContainer = 
    std::same_as<std::remove_cvref_t<Container>, std::list<typename Container::value_type>> ||
    std::same_as<std::remove_cvref_t<Container>, std::forward_list<typename Container::value_type>>;

template <ListContainer Container>
void prinList(Container list) {
    for (auto var : list) { std::cout << var << " "; }
    std::cout << '\n';

    using T = typename Container::value_type;
    std::vector<T> vec;
    auto it1 = list.begin();
    auto it2 = list.end();
    vec.assign(it1, it2);
}

int main(){
    std::forward_list<int> F_list1={1,2,3,4,5};
    prinList(F_list1);

    std::list<int> list1={10,11,12,13};
    prinList(list1);

    // 以下代码会编译报错,因为std::vector不符合ListContainer约束
    // std::vector<int> vec1={1,2,3};
    // prinList(vec1);

    return 0;
}

说明

  • ListContainer概念明确限制了可传入的容器类型,若尝试传入其他容器(如std::vector),编译器会直接抛出错误,避免误用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:15:07