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

C++使用STL容器作为模板模板参数定义函数时匹配失败问题

问题原因

你遇到的编译报错是由模板模板参数的匹配规则导致的:
你声明的模板模板参数template <typename> class Container要求传入的容器模板仅接受1个类型参数,但C++标准库中的所有序列容器(vector/list/deque等)实际有2个类型参数,第二个为分配器参数,带默认值,因此不满足你的模板参数匹配要求,触发模板替换失败。

修复方案

调整模板模板参数的声明,兼容标准容器的多参数结构:
将函数模板的声明修改为:

// C++11及以上版本通用写法,用可变参数匹配多余的默认模板参数
template<template <typename, typename...> class Container = vector>

如果你需要兼容C++03,可以使用指定默认分配器的写法:

template<template <typename, typename = std::allocator<std::string>> class Container = vector>
完整修改后可运行代码
#include<string>
#include<iostream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<algorithm> // 需包含algorithm头文件使用copy
#include<iterator>  // 需包含iterator头文件使用back_inserter

using namespace std;

template<template <typename, typename...> class Container = vector>
Container<string> filter_codes(const string& route, const char& init) {
    Container<string> _return;
    vector<string> temp;
    ifstream file(route);

    string wd;
    while(file >> wd){
        if(wd[0] == init)
            temp.push_back(wd);
    }
    // 优化:用back_inserter替代resize+copy,避免部分容器不支持resize的问题
    copy(temp.begin(), temp.end(), back_inserter(_return));
    file.close();
    return _return;
}

int main(){
    // 两种你期望的调用方式都可以正常运行
    vector<string> t1 = filter_codes("a.txt", 'x');
    auto t2 = filter_codes<list>("a.txt", 'x');
    return 0;
}
额外说明
  • 代码中补充了algorithm和iterator头文件引入,避免部分编译器找不到copy和back_inserter的报错
  • 如果需要支持forward_list,需要单独调整插入逻辑,因为forward_list不支持push_back操作,需要改用front_inserter插入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:39:01