dimanche 3 mai 2020

Why am I getting a bad_function_call exception when using std::function as a comparison function object in std::map

I am getting a std::__1::bad_function_call: std::exception when I execute the code below.

I have tried initializing std::function in the constructor and initializing it directly when defined as a class variable. In both cases I get the aforementioned exception.

Note that if I define a function object (a class with a bool operator () function defined), the code works properly. How can I capture a lambda into std::function so that no exception is thrown? Also, what is causing the exception in the code below?

#include <map>
using namespace std;

class foo {
public:
    foo() {cmp = [](const int &a, const int &b){return a > b;};}
    //function<bool(const int &a, const int &b)> cmp = [](const int &a, const int &b){return a > b;};
    function<bool(const int &a, const int &b)> cmp;
    map<int, int, decltype(cmp)> rbtree;
};

int main() {

  foo* obj = new foo();
  obj->rbtree[5] = 5;
  obj->rbtree[1] = 5;
  obj->rbtree[5] = 5;
}

Aucun commentaire:

Enregistrer un commentaire