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

C++自定义模板类Dictionary调用add()提示无匹配函数报错如何解决

错误原因

  • 类型不匹配
    你在main函数中实例化Dictionary时指定的模板参数是vector<int>(键类型)和vector<string>(值类型),对应add方法的签名是void add(vector<int> key, const vector<string> &value),但你调用add时传入的参数是int类型的key和string类型的part,参数类型完全不匹配,编译器找不到符合调用签名的函数,因此抛出该错误。
  • 模板实现分离的潜在问题
    即使你修复了类型问题,后续也会出现链接错误:C++模板的声明和实现不能分离到独立的.h和.cpp文件,除非提前做了显式实例化,否则编译器在编译main.cpp时看不到模板的实现代码,无法生成对应类型的实例化代码。

修复方案

  1. 修改main函数中Dictionary的实例化代码,替换为你实际需要的键值类型:
// 原错误声明
// Dictionary <vector<int>, vector<string > > part1;
// 修改后声明,键为int类型,值为string类型
Dictionary <int, string> part1;
  1. 将Dictionary.cpp中的所有模板实现代码移动到Dictionary.h中类声明的下方,删除独立的Dictionary.cpp文件,避免后续链接错误。修改后的Dictionary.h示例如下:
#include <vector>
#include <string>
#include <iostream>

template <class A,class B>
class Dictionary
{
    public:
        Dictionary();
        void add(A key,  const B &value);
        B find (A key) const;
        void display();
    
    private:
        std::vector<A> keys;
        std::vector<B> values;
};

template <class A,class B>
Dictionary<A,B>::Dictionary()
{
    //nothing to do, vector member variables are empty on declaration
};

template <class A,class B>
void Dictionary<A,B>::add(A key,  const B &value)
{
    keys.push_back(key);
    values.push_back(value);
}
    
template <class A,class B>
B Dictionary<A,B>::find (A key) const
{
    B value = B();
    for (unsigned int i = 0; i < keys.size(); i++)
        if (key == keys[i])
            value = values[i];
    return value;
}

template <class A,class B>
void Dictionary<A,B>::display()
{
    for (unsigned int i = 0; i < keys.size(); i++)
        std::cout << keys[i] << ' ' << values[i] << std::endl;
    return;
}
  1. 可选优化:
  • 删除头文件中的using namespace std;,改用std::前缀标注标准库类型,避免命名空间污染。
  • 原find函数中硬编码了字符串默认返回值,仅支持值类型为string的场景,修改为返回默认构造的B类型,适配通用场景;如果需要支持找不到的提示逻辑,可以改为抛出异常,或者使用C++17的std::optional包装返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:45:02