C++ 重构采用 int 或字符串参数的方法

C++ Refactoring a method that takes either an int or string argument

本文关键字:字符串 参数 方法 int 重构 C++      更新时间:2023-10-16

我一直在努力创建一个程序来存储学生的集合。我意识到我本质上使用相同的复制/粘贴代码为我的各种类容器创建基本相同的方法。我决定重构代码并重新设计了大部分代码。我目前面临的问题是使用我的搜索方法。对于我的一些集合,搜索方法获取并返回一个整数 ID(例如学生编号),而其他集合获取并返回字符串 ID(例如课程代码)。我一直在试图弄清楚如何创建一个可以处理这两种情况的单一方法。

我基本上想要下面的代码,但我希望它获取并返回传递给它的类型(int 或字符串)。请注意,getID() 只是一个用于从学生班级返回学生 ID 或从课程类返回课程代码的方法。

template <typename S>
S * findID([string or int] ID){
    for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
        if((*element)->getID() == ID) return *element;
    return NULL;
}
您可以使用

模板,例如:

template <typename Collection, typename ID>
auto* find_by_id(Collection& collection, const ID& id)
{
    auto it = std::find_if(std::begin(collection), std::end(collection),
                        [&](const auto* e) { return e->getID() == id; })
    if (it == std::end(collection)) {
        return nullptr;
    }
    return *it;
}