I am trying to save callbacks for later use in a class and run into the problem that the linker apparently can't see all the symbols it needs. The callbacks are member-functions of another object. If i hand a std::function over to the method registering the callback everything works fine. If I try to move the call to std::bind into the method and only pass the arguments to std::bind I get LNK2019 on MSVC2019.
The Class that stores the callbacks looks like this: Class1.h
#ifndef CLASS1_H
#define CLASS1_H
#include <functional>
#include <string_view>
class Class1
{
public:
using Callback_t = std::function<void(std::string_view)>;
Class1();
template<typename T>
void addCallback(T * obj, void (T::*func)(std::string_view));
void addCallback(Callback_t callback);
void doStuff(std::string_view text);
private:
Callback_t m_callback;
};
#endif // CLASS1_H
Class1.cpp
#include "Class1.h"
Class1::Class1()
{
}
template<typename T>
void Class1::addCallback(T * obj, void (T::*func)(std::string_view))
{
m_callback = std::bind(func, obj, std::placeholders::_1);
}
void Class1::addCallback(Callback_t callback)
{
m_callback = callback;
}
void Class1::doStuff(std::string_view text)
{
m_callback(text);
}
The object of which I take the callback looks like this: Class2.h
#ifndef CLASS2_H
#define CLASS2_H
#include <string_view>
class Class2
{
public:
Class2();
void display(std::string_view text);
};
#endif // CLASS2_H
Class2.cpp
#include "Class2.h"
#include <iostream>
Class2::Class2()
{
}
void Class2::display(std::string_view text)
{
std::cout << "The text was: " << text << std::endl;
}
The classes are both used from this file. main.cpp
#include "Class1.h"
#include "Class2.h"
int main(int argc, char *argv[])
{
Class1 obj1;
Class2 obj2;
obj1.addCallback(&obj2, &Class2::display); //results in linker error
obj1.addCallback(std::bind(&Class2::display, &obj2, std::placeholders::_1)); //works
obj1.doStuff("wallalalalalalla!!!!");
}
Is there any solution to achive the call that only uses the pointer to the object and the pointer-to-member-function instead of the std::function?