Between two certain repos I've so far used an interface class (with inheritance), and this I've recently replaced with a callback function using std::function() & std::bind().
Using the old, interface-like method I ended up with this:
//a.hpp
#include "b.hpp"
class A{
public:
A(InterfaceB* pb) : m_pb(pb) {};
void bar(){m_pb->foo();};
private:
InterfaceB* m_pb;
};
--
//b.hpp
#include <iostream>
class InterfaceB{
public:
virtual void foo() = 0;
};
class B : public InterfaceB {
public:
void foo(){ std::cout << "hi"<< std::endl; };
};
--
//main.cpp
#include "a.hpp"
#include <memory>
int main(){
InterfaceB* pb = new B;
A a(pb);
a.bar();
delete pb;
}
--
In UML, I'd draw the little example above like this:
To reduce dependency between the repos (here A and B classes) I'd dropped the interface and used a function wrapper instead.
//a_callback.hpp
#include <functional>
class A{
public:
void setBcallback(std::function<void(void)> callback){m_callback = callback;};
void bar(){m_callback();};
private:
std::function<void(void)> m_callback;
}
--
//b_callback.hpp
#include <iostream>
class B {
public:
void foo(){ std::cout << "hi"<< std::endl; };
}
--
//main.cpp
#include "a_callback.hpp"
#include <functional>
int main(){
A a;
B b;
a.setBcallback(std::bind(&B::foo, &b));
a.bar();
}
--
And this has been the tricky bit for me, I had no luck on Google finding how C++'s std::bind()/std::function() and UML's << bind >> translate to each other. So my question would be, how would one show the use of a function wrapper on a class diagram? Based on what I've found I'd probably go with this:
But it just feels loose and insufficient. Any help would be much appreciated!
This question has been previously marked as a duplicate with this: How to represent Callback in UML Class Diagram . But my question is C++ specific and said 'original' is tagged as Java, unfortunately I got no help from that. My question was not 'how to show a callback in UML' that I think it explains , but more of 'how to show the std::bind() in UML' which I think is trickier. There's two things going on here, one is setting up the function wrapper with bind(), second the call via the wrapper. I just couldn't see how that thread above addresses this specific question. Thank you!