I've spent some time trying figure out how to do this but I think I need help. If I could use templates I can avoid having to type the function, like 'B::theFuncToBeCalled', right? But that only works if it's a static method, if I'm not mistaken?
// A.h
typedef std::function <void()> CbType;
class A
{
template<typename T>
void setCallback(T &cb);
private:
template <typename T>
T callThisLater;
};
// A.cpp
template<typename T>
void A::setCallback(T &cb)
{
this->callThisLater = cb;
// later...
((CbType*)callThisLater)();
}
// B.cpp
// in constructor or wherever
{
A* a;
a->setCallback(this->theFuncToBeCalled);
// or, anonymous
CbType func = [this](){
// do something
// call theFuncToBeCalled() if I feel like it :)
};
a->setCallback(func);
}
void B::theFuncToBeCalled()
{
log("yay");
}
(If I try doing it the anonymous way I get an access violation error.)
There is much wrong here. Let's discuss that and then how to fix it:
You cannot simply define templatized functions in the implementation file: https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
c++14's variable templates are only available for static variables:
A variable template defines a family of variables or static data members
You are passing a method, and trying to use it as though you passed a function, methods implicitly take the this parameter
Once the type of callThisLater is defined to accept a method, it cannot be subsequently changed to accept a lambda with a different signature
class A is a poor re-implementation of what could be solved with a functor or even just a function pointer
Please simply eliminate class A and use a function pointer and a closure type:
auto a = &B::theFuncToBeCalled;
auto func = [=]() { (*this.*a)(); }
Rather than using a going forward simply use func
I decided to change my approach and instead of saving a pointer to a callback, I'm saving a pointer to the object the member function belongs to. It's the same amount of work, but with the benefit that if I ever need to call several different member functions, I can just do:
objRef->theFuncToBeCalled();
// later
objRef->theOtherFuncToBeCalled();
and all I need for this, is one pointer. Simple is Bestâ„¢, amiright? :) Thanks for your help!
Related
to my understanding a member function is different to a normal function because there is an additional this pointer parameter.
So my idea is to make is make the following member template function to one of my classes:
template <class T>
void ApplyFunction(function<void(vector<int>&, T)> fun, T val);
and then I will use it inside one of my classes like:
Thing.ApplyFunction(myMethod, this);
and Thing will use the myMethod from my current class instance.
A lot of this code is guesswork so I would like some clarification as to if this would work. Also not sure which way round it is:
void ApplyFunction(function<void(vector<int>&, T)> fun, T val);
or
void ApplyFunction(T val, function<void(vector<int>&, T)> fun);
A code sample describing why I might want something like this:
void ClassA::callbackMethod(vector<int> &array)
{
//I can edit the array here
}
void ClassA::someMethod(void)
{
ClassB B;
B.ApplyFunction(callbackMethod, this);
//now whenever B wants to edit the array, it can by using callbackMethod
B.ComplicatedStuff(); // B uses the callbackMethod multiple times here
}
It looks to me like you are just planning to invoke a method, and you don't need to store the callable. If that is the case you should not use std::function but simply take a callable as a template parameter.
template <class T>
void ApplyFunction(T&& func) {
func(/*pass in your vector here*/);
}
With that you can you can then call it from A by passing in a lambda.
void ClassA::someMethod(void)
{
ClassB B;
B.ApplyFunction([&](std::vector<int>& vec){
// do stuff with vec here
// or call a member function
callbackMethod(vec);
vec.push_back(2);
});
}
This will be faster since passing by template parameter like this gives almost no additional cost from just a normal function call. If the function is inline it can be as cheap as just calling a member function.
std::function is a type-erased wrapper for any callable and comes with overhead, only use it if you need to store the callable for later use.
Edit
If you like to store the function, you don't need a template, you can simply take a std::function as parameter in ApplyFunction.
void ApplyFunction(std::function<void(std::vector<int>&)> func) {
//Store it, call it now or call it later.
m_func = func;
m_func(/*pass in your vector here*/);
}
Call it the same way, with a lambda.
Using a lambda like this is the preferred method when binding a member function to an instance. Instead of passing this separately it's better to wrap it in a lambda and get it for free so to speak.
sorry for possible duplicates, but I didn't understand the examples and codes snippets I found.
I have a class named "EncoderWrapper" which includes some functions. One of these functions is called "onAfterTouch" and is declared in the "EncoderWrapper.h" file.
void onAfterTouch(byte channel, byte pressure);
The functions will become a callback for another class function of a library I use
inline void setHandleAfterTouch(void (*fptr)(uint8_t channel, uint8_t pressure)) {
usb_midi_handleAfterTouch = fptr;
};
Note: I'm totally new to C++, so I want to say sorry if I'm doing some "no-gos" or mixing up some terms.
The question is: How can I pass my class function (member function?) to that "setHandleAfterTouch" function of the library?
This won't work:
void EncoderWrapper::attachMIDIEvents()
{
usbMIDI.setHandleAfterTouch(&EncoderWrapper::onAfterTouch);
}
... my IDE says
no matching function for call usb_midi_class:setHandleAfterTouch(void (EncoderWrapper::*)(byte, byte))
I've also tried
usbMIDI.setHandleAfterTouch((&this->onAfterTouch));
But this won't work ... and I don't get the approach on that.
Every Help is very appreciated ;-)
Function pointer and member function pointer have different types. You can it for yourself:
struct Test {
void fun();
};
int main() {
void(*ptr)() = &Test::fun; // error!
}
Instead, member function pointer need this syntax:
void(Test::*fun)() = &Test::fun; // works!
Why you ask? Because member function need an instance to be called with. And calling that function have a special syntax too:
Test t;
(t.*funptr)();
To accept member function pointer, you'll need to change your code to this:
inline void setHandleAfterTouch(void(EncodeWrapper::*fptr)(uint8_t, uint8_t)) {
usb_midi_handleAfterTouch = fptr;
};
Since it's rather limiting accepting only the functions from one class, I recommend using std::function:
inline void setHandleAfterTouch(std::function<void(uint8_t, uint8_t)> fptr) {
usb_midi_handleAfterTouch = std::move(fptr);
};
This will allow you to send lambda with captures, and call your member function insode it:
// we capture this to use member function inside
// v---
usbMIDI.setHandleAfterTouch([this](uint8_t, channel, uint8_t pressure) {
onAfterTouch(channel, pressure);
});
It seems you can't change, and by looking quickly at the API, it doesn't seem you have access to a state object.
In that case, if you want to use your member function, you need to introduce a global state:
// global variable
EncodeWrapper* encode = nullptr;
// in your function that sets the handle
encode = this; // v--- No capture makes it convertible to a function pointer
usbMIDI.setHandleAfterTouch([](uint8_t, channel, uint8_t pressure) {
encode->onAfterTouch(channel, pressure);
});
Another solution would be to make onAfterTouch function static. If it's static, it's pointer is not a member function pointer, but a normal function pointer.
I have a class which shall invoke a function specified by the user on certain occasions. Therefore the class has a method void setExternalPostPaintFunction(void(*function)(QPainter&)); that can be used to "register" a function. This function then will be called on that occasion:
class A {
public:
void setExternalPostPaintFunction(void(*function)(QPainter&));
private:
void (*_externalPostPaint)(QPainter&);
bool _externalPostPaintFunctionAssigned;
};
The function pointer is saved in the member variable _externalPostPaint. The implementation of setExternalPostPaintFunction looks like this:
void A::setExternalPostPaintFunction(void(*function)(QPainter&)) {
_externalPostPaint = function;
_externalPostPaintFunctionAssigned = true;
}
Now, this works with normal functions. However, I want to be able to also pass pointers to member functions of objects. From what I know I also have to pass and store the pointer to the object in this case. However, I don't know which type the other object will have. So I guess I'm forced to use templates. I already thought of something like this:
class A {
public:
template <typename T>
void setExternalPostPaintFunction(void(T::*function)(QPainter&), T* object);
private:
void (T::*_externalPostPaint)(QPainter&); //<- This can't work!
bool _externalPostPaintFunctionAssigned;
};
This way I can pass a function pointer and an object pointer to setExternalPostPaintFunction and would probably be able to call the function on the object inside that function. But I'm not able to store it in the variable _externalPostPaint because the type T is only deduced when the function setExternalPostPaintFunction is called, thus I can't have a member variable that depends on this type, since the type of my member variable has to be known when the object is created and apart from that it cannot change, but it would have to in the case when a new function is assigned which possibly could be a member function of an object of different type.
So what is the proper way to do this, or is there any? I'm not super fit with templates and function pointers, so I might have overlooked something.
Anoter option would certainly be to create a functor class with a virtual member function which can be overwritten in a derived class and then pass + store an object pointer of that type instead of the function pointer. But I somehow would prefer my approach if it is somehow possible.
EDIT: SOLUTION
TartanLlama brought me on the right track by suggesting the use of std::function. Here is how I solved it:
class A {
public:
template <typename T>
void setExternalPostPaintFunction(T* object, void(T::*function)(QPainter&)) {
_externalPostPaint = std::bind(function, object, std::placeholders::_1);
_externalPostPaintFunctionAssigned = true;
}
void setExternalPostPaintFunction(std::function<void(QPainter&)> const& function);
private:
std::function<void(QPainter&)> _externalPostPaint;
bool _externalPostPaintFunctionAssigned;
};
As you see, the pointer to the function/member function is stored in an std::function<void(QPainter&)> object now. The advantage is, that an std::function can basically store any callable target. Then there are two overloads: one that can be used for any std::function object that also accepts e.g. a normal function pointer (because the std::function that is expected then is implicitly constructed from that) and one for member functions that have to be called on an object (more for convenience). The latter is implemented as a template. This uses std::bind to create a std::function object of the call of that member function (the user passed) on the object (the user passed).
The overload that takes an std::function is implemented in the source file like this:
void ImageView::setExternalPostPaintFunction(std::function<void(QPainter&)> const& function) {
_externalPostPaint = function;
_externalPostPaintFunctionAssigned = true;
}
Invoking that stored function in the code of class A is now as simple as that:
//canvas is a QPainter instance
if (_externalPostPaintFunctionAssigned) _externalPostPaint(canvas);
The user who wants to register a member function as callback function just has to do the following:
//_imageView is an instance of "A"
//"MainInterface" is the type of "this"
_imageView->setExternalPostPaintFunction(this, &MainInterface::infoPaintFunction);
Or if it's not a member function but just a normal function:
void someFunction(QPainter& painter) {
//do stuff
}
_imageView->setExternalPostPaintFunction(&someFunction);
Or he can explicitly create a std::function object and pass it:
std::function<void(QPainter&)> function = [&](QPainter& painter){ this->infoPaintFunction(painter); };
_imageView->setExternalPostPaintFunction(function);
Works like a charm.
You could use std::function:
class A {
public:
//PostPaintFun can be anything which acts as a function taking a QPainter&
//Could be a lambda, function pointer, functor, etc.
using PostPaintFun = std::function<void(QPainter&)>;
void setExternalPostPaintFunction(PostPaintFun fun);
private:
//Names beginning with an underscore are reserved, don't use them
//Ending with an underscore is fine
PostPaintFun fun_;
bool externalPostPaintFunctionAssigned_;
};
Now you can use member functions like so:
struct B
{
void exec(QPainter&) const;
};
void foo() {
B b;
a.setExternalPostPaintFunction(
[b] (QPainter& p) {b.exec(p);}
);
}
//or inside B
void B::foo() {
a.setExternalPostPaintFunction(
[this] (QPainter&p) {this->exec(p);}
);
}
I have to say I prefer TartanLlama's answer, but here you have something it could work for you.
This might to need some work, but I'm sure you'll get the idea.
struct IFunctionHolder {}; // Used for pointing to any FunctionHolder
typedef IFunctionHolder* functionHolder_ptr; // Alias for IFunctionHolder* .
template<typename Function> // The template for the actual function holders.
struct FunctionHolder: public IFunctionHolder
{
Function function;
};
class A {
public:
template <typename T>
void setExternalPostPaintFunction(void(T::*function)(QPainter&), T* object);
private:
functionHolder_ptr *function_holder; // This memeber can hold eny instantiation of template<> FunctionHolder.
// Instantiate this member wen calling setExternalPostPaintFunction
bool _externalPostPaintFunctionAssigned;
};
You could have some code like this:
A some_a;
void some_a.setExternalPostPaintFunction(&SomeInstance::some_fnunction); // Here take place the instantiation of FunctionHolder.
some_a.function_holder.function(some_painter);
I have to create objects of three-four classes, all inherited from one base class, but some of the objects need to have different behavior - like complete change of one function; I can do this through more inheritance and polymorphism, but it doesn't seem like a good idea.
My first solution was to use specialized templates(for every nonstandard case), but then I have though about lambdas as template parameter(like here: Can we use a lambda-expression as the default value for a function argument? ) and use them instead class method(like here: C++11 lambda and template specialization ) - for me it's much better solution, because I only have to pass lambda for every weird situation:
auto default_lambda = [&]() -> int {return this->Sth;};
template<typename functor = decltype(default_lambda)>
class SomeClass{
...
Problem is with this pointer - method which I want to change need access to non-static methods and lambda is defined outside of non-static method. Moreover, I can't pass reference to class to lambda, because it's a template class(or maybe I'm wrong?).
Of course, I can use specialized template or just function pointers, but I really like solution with lambdas and I consider it much more fine than my other ideas.
Is there any way to "avoid" this problem? Or maybe my idea was bad all along?
There are at least three obvious problems with your approach:
The class SomeClass won't get access to private members, i.e. use of this is out of question.
You attempt to bind this from the context but there is no context i.e. nothing bind to. You will have to pass the object to dealt with a function parameter.
You only specified a type of the function object but no instance, i.e. you won't be able to use it later.
That said, it seems you could just use the type of a custom function object type rather than some lambda function (sure, this is absolutely unsexy but in return it actually works):
struct default_lambda {
template <typename T>
int operator()(T const& o) const { return o.x(); }
};
template <typename F = default_lambda>
class SomeClass {
...
};
If you need complete change of one function, you have two choices:
One virtual function, using perhaps local classes + type erasure if you have many such objects and you don't want to create many namespace scope types:
std::function, which can be rebound later if you wish.
Example code for the first solution (you can even make this a template):
std::unique_ptr<my_base2> get_an_object()
{
class impl : public my_base2
{
void my_virtual_function() { blah blah; }
};
return std::unique_ptr<my_base2>(new impl);
}
Both are generally superior to templates in this situation (but without context it is hard to tell).
I'm using a 3rd party library that allows me to register callbacks for certain events. The register function looks something like this. It uses the Callback signature.
typedef int (*Callback)(std::string);
void registerCallback(Callback pCallback) {
//it gets registered
}
My problem is that I want to register a member function as a callback something like this
struct MyStruct {
MyStruct();
int myCallback(std::string str);
};
MyStruct::MyStruct() {
registerCallback(&MyStruct::myCallback);
}
int MyStruct::myCallback(std::string str) {
return 0;
}
Of course, the compiler complains, saying
error C2664: 'registerCallback' : cannot convert parameter 1 from 'int (__thiscall MyStruct::* )(std::string)' to 'Callback'
I've been looking at boost libraries like function and bind, but none of those seem to be able to do the trick. I've been searching all over Google for the answer, but I don't even know what to call this, so it hasn't been much help.
Thanks in advance.
You're trying to pass a member function pointer as a normal function pointer which won't work. Member functions have to have the this pointer as one of the hidden parameters, which isn't the case for normal functions, so their types are incompatible.
You can:
Change the type of your argument to accept member functions and also accept an instance to be the invoking object
Quit trying to pass a member function and pass a normal function (perhaps by making the function static)
Have a normal function that takes an instance of your class, a member function pointer, and a std::string and use something like boost's bind to bind the first two arguments
Make the callback registration function accept a functor object, or an std::function (I think that's the name)
Numerous other ways which I won't detail here, but you get the drift.
Member functions are not convertible to the normal functions for its own good reasons. If your design allows, then make MyStruct::myCallback() a static member method and the code should work fine.
struct MyStruct {
...
static int myCallback(std::string str);
^^^^^^
};
Due to the inflexible hardcoding of an actual function type for the callback you can't use any of the normal adapting or binding tricks to help you here. The third party library really wants you to pass in a non-member function and there isn't much you can do. You may want to consider why you're trying to pass it the address of a member function, and if your design or use of the library could change.
One option, if you only need to set a single callback, is to have a static or namespace private function that refers to a singleton instance pointer, and uses that to dispatch upon callback.
If you need multiple items, then possibly a template would wrap the hackiness (untested code here, just the idea).
template <int which_callback>
struct CallbackHolderHack
{
static int callback_func(std::string str) { dispatchee_->myCallback(str); }
static MyStruct* dispatchee_;
};
template <int which_callback>
MyStruct* CallbackHolderHack::dispatchee_(0);
And use it:
CallbackHolderHack<0>::dispatchee_ = new MyStruct;
registerCallback(&CallbackHolderHack<0>::callback_func);
Depends on how you are using it.... eg a Singlton would be much simplier
struct MyStruct {
static MyStruct& Create() {
static MyStruct m; return m;
}
static int StaticCallBack(std::string str) {
return Create().Callback(str)
}
private:
int CallBack(std::string str);
MyStruct();
};
Or if you want to have many of these objects you have several choices. You would need a way to route it before the callback is called.
Since you are using C++, why not make the callback a functor object? Then you can use std::mem_fun.
Edit: Seems std::mem_fun has been deprecated in the latest C++11 standard. So std::function might be a better solution if you have a new compiler.
See this SO question for hints about using it.
class ICallBackInterface
{
public:
virtual void FireCallBack( std::string& str ) = 0;
};
std::set<ICallBackInterface*> CallBackMgr;
class MyStruct : public ICallBackInterface
{
public:
MyStruct()
{
CallBackMgr.insert( this );
}
~MyStruct()
{
CallBackMgr.erase( this );
}
virtual void FireCallBack( std::string& str )
{
std::cout << "MyStruct called\n";
}
};
void FireAllCallBack(std::string& str )
{
for ( std::set<ICallBackInterface*>::iterator iter = CallBackMgr.begin();
iter != CallBackMgr.end();
++iter)
{
(*iter)->FireCallBack( str );
}
}
This is another way to use polymorphism to achieve the same effect