I am a hobbyist programmer and a little knowledge is a dangerous thing. I wanted to include a user defined compare function into my class (e.g. std::less). So, I wrote a test program:
#include "pch.h"
#include <iostream>
#include <functional>
bool myfunc(const int& a, const int& b) {
return a < b;
}
template <class K>
class myclass
{
public:
myclass(const std::function<bool(const K&, const K&)>& fn);
const std::function<bool(const K&, const K&)>& comp;
};
template <class K>
myclass<K>::myclass(const std::function<bool(const K&, const K&)>& fn) : comp(fn)
{
}
using std::cout;
int main()
{
myclass<int> foo(myfunc);
cout << std::boolalpha << myfunc(1, 2) << "\n";
cout << std::boolalpha << foo.comp(1, 2) << "\n";
cout << "Hello World!\n";
}
The program compiles. myfunc works as expected. However, I got the following run-time error message:
Exception thrown at 0x75BAB022 in forward.exe: Microsoft C++ exception: std::bad_function_call at memory location 0x00B4F5F4.
Unhandled exception at 0x75BAB022 in forward.exe: Microsoft C++ exception: std::bad_function_call at memory location 0x00B4F5F4.
Yes, I have searched for answers, no I have not found something that I understand. Any help would be appreciated. (Written in VS17, with c++17 turned on.)