首页 > 解决方案 > 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++;
        }
    }
}

标签: c++templates

解决方案


模板不像你想象的那样工作。要拥有您想要的界面,您需要两个功能(如果您愿意,可以使用助手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需要在编译时设置,所以如果你在你做的地方声明它们t1t2就不能拥有正确的类型。

请注意,您的代码还有其他一些地方在我看来仍然是错误的。这足以解决您的问题所涉及的编译器错误。


推荐阅读