C++ 仿函数和列表模板

标签 c++ templates functor

我已经实现了一个列表和迭代器模板,find 方法应该接收一个仿函数,所以我声明并实现了一个仿函数,但我一直收到没有这样一个对象的错误! “没有匹配函数来调用 const findBond 类型的对象

下面是查找方法的实现:

template <class T>
template <class Predicate>
Iterator<T> List<T> :: find(const Predicate &predicate) {
    for (Iterator<T> iterator=begin(); iterator != end(); ++iterator) {

        if (predicate(*iterator)) {

            return iterator;

        }

    }

    return end();

}

// predicate is a functor that is supposed to return a boolean value

这是函数对象:

class findBond{

    Bond& bond;

public:

    findBond( Bond& bond1) : bond(bond1) {}

    bool operator() (Bond& bond1){

            return bond==bond1;

            }
};

我在这里尝试使用它们:

void InvestmentBroker :: addBond(const string& name, double value, int amount ){
    Bond bond = *new Bond(name, value, amount);

    if (bondsDatabase.find(findBond(bond)) != bondsDatabase.end()) {

        //throw an exception

    } else { 

       // insert bond to dataBase

    }
}

我包含了所需的文件,所以这与包含无关

怎么了?我在这里错过了什么?

最佳答案

您的查找方法将 const Predicate& 作为其参数。这意味着您只能调用谓词的 const 方法。但是,您的仿函数的调用运算符未声明为 const。您可以通过像这样声明 const 来解决您的问题:

bool operator() (Bond& bond1) const {/* do stuff */ }

声明末尾的 const 意味着您不能在函数内修改 this,这反过来意味着您可以在 const 对象。

关于C++ 仿函数和列表模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31106205/

相关文章:

c++ - 导入C++模块,如果失败: import Python version?

c++ - 在 ICU 中使用文字字符串

c++ - 如何检查一个类是否具有一个或多个具有给定名称的方法?

c++ - connect(QObject*, SIGNAL(signal()), functor) 在 qt5 中没有连接

c++ - 将 std::bind 创建的对象传递给函数的正确方法是什么?

c++ - 为什么标准不将模板构造函数视为复制构造函数?

c++ - 是否可以使用 boost 构建并发进程间消息队列?

c++ - 从派生类调用时推断 'this' 指针类型?

c++ - 如何在 C++ 中实现公式模式?

c++ - 如何将模板参数包转换为函数的多个指针参数?