c++ - C++ 模板 - 未找到匹配的重载函数,无法推断“T”的模板参数
问题描述
我正在尝试实现“比较”功能。取决于输入参数,比较目标可以是 2 个类之一。这就是为什么我想使用模板来简化代码维护。我是模板新手,不知道发生了什么。
class Compare_Output
{
public:
static Directory* empty_dir;
static File* empty_file;
enum COMPARE_TYPE { FILE, SUB_DIR };
Directory* dir1;
Directory* dir2;
int level;
std::pair<std::string,std::string> dir_name;
std::vector<Compare_Output> sub_dir_compare;
std::vector<File_Compare_Result> list;
Compare_Output(Directory* dir1, Directory* dir2, int level);
template<class T>
void compare(int type, int level);
Compare_Output& operator=(const Compare_Output&) = default;
};
class Directory
{
public:
fs::path path;
Directory* parent;
std::vector<Directory*> sub_dir;
std::vector<File*> files;
Directory(const fs::path path, Directory* parent = NULL);
Directory& operator=(const Directory&) = default;
std::string getDirName(void);
static void compare(Directory& dir1, Directory& dir2, std::vector<Compare_Result> &result);
static void getAllFiles(Directory& dir, std::vector<std::pair<File*, int>>& result, int level, bool include_dir); // use for root directory only, thus make it static
};
template<class T>
void Compare_Output::compare(int type, int level)
{
int i = 0, j = 0;
std::vector<T*> t1, t2;
if (type == FILE)
{
t1 = dir1->files;
t2 = dir2->files;
}
else if (type == SUB_DIR)
{
t1 = dir1->sub_dir;
t2 = dir2->sub_dir;
}
while (!(i == t1.size() && j == t2.size()))
{
// avoid the out of bound error
if (i == t1.size() && i != 0)
i--;
if (j == t2.size() && j != 0)
j--;
T* item1 = t1.at(i);
T* item2 = t2.at(j);
if (*item1 == *item2)
{
list.push_back({ true, item1, item2 });
i++;
j++;
}
}
}
解决方案
模板不像你想象的那样工作。要拥有您想要的界面,您需要两个功能(如果您愿意,可以使用助手private
),如下所示:
template<class T>
void Compare_Output::compare_helper(std::vector<T*> t1, std::vector<T*> t2, int level)
{
int i = 0, j = 0;
while (!(i == t1.size() && j == t2.size()))
{
// avoid the out of bound error
if (i == t1.size() && i != 0)
i--;
if (j == t2.size() && j != 0)
j--;
T* item1 = t1.at(i);
T* item2 = t2.at(j);
if (*item1 == *item2)
{
list.push_back({ true, item1, item2 });
i++;
j++;
}
}
}
void Compare_Output::compare(int type, int level)
{
if (type == FILE)
{
compare_helper(dir1->files, dir2->files, level);
}
else if (type == SUB_DIR)
{
compare_helper(dir1->sub_dir, dir2->sub_dir, level);
}
}
你的方法不起作用的原因type
是它只在运行时知道,但T
需要在编译时设置,所以如果你在你做的地方声明它们t1
,t2
就不能拥有正确的类型。
请注意,您的代码还有其他一些地方在我看来仍然是错误的。这足以解决您的问题所涉及的编译器错误。
推荐阅读
- c# - ASP.NET WPF - 带有圆角半径的图像溢出边框
- node.js - 尝试通过服务器端渲染渲染页面时 jsdom 中的内存泄漏
- docker - docker 与 freebsd 10 兼容吗?
- javascript - 当字段为空并使用 Ajax 发布时,checkValidity() 不显示任何 html5 错误通知
- typescript - 对象属性路径的 TypeScript 类型定义
- gitlab - 将源代码和历史从一个 GitLab 项目复制到另一个
- flutter - 如何使bottomNavigationBar缺口透明
- python - 带有 Tkintertable 的 Python 中包含一些空行的 CSV 文件
- r - 在向量中写入与矩阵中的行一样多的 1
- php - Netatmo Api - 如果温度 X 则需要 Hlep,否则