Missing call to bound pointer to member function - c++

I am trying to implement a generic event handling system with templates, but I get an error at compile time when I try to add the function to a list.
error C2298: missing call to bound pointer to member function
class EventManager
{
public:
template <class OBJECT>
void subscribe(std::string eventName, OBJECT *obj, void(OBJECT::*newEvent)(Event))
{
(obj->*newEvent)(Event()); // I can call the event just fine if I execute it alone
abc.push_back(obj->*newEvent); // Error c2298 here
}
static EventManager* Get();
private:
std::vector<void(*)(Event)> eventsList;
};
And this is where I call it:
EventManager::Get()->subscribe("EventName", this, &TestClass::eventTest);
void ATideManager::eventTest(Event event)
{
//Test
}
I am quite new to C++ and templates, so I'm sure the solution is easy, but I don't understand why I can call the event but not add it to the vector. Do you know how I could possibly do that?

As the documentation for that error message says:
A pointer to member-function expression must call the member function.
In other words, you cannot store a pointer to member-function including the object on which to call it, for later use.
Here is a simpler example using names similar to yours:
struct Object
{
void f() {}
};
int main()
{
Object obj;
using member_function_pointer = void (Object::*)();
member_function_pointer ptr = &Object::f;
(obj.*ptr)();
(obj.*ptr); // error
}
And this makes a lot of sense. Your abc is probably a vector of pointers to member-function (or just a vector of function pointers); it cannot magically store an object along with each pointer in it.
Generally, pointers to member functions are not exactly the nicest, cleanest or best feature of C++, and the awful syntax renders every piece of code using it completely unreadable. Fortunately, C++11 introduced std::function and lambdas, which gives you a much better alternative:
#include <functional>
#include <iostream>
#include <string>
#include <vector>
struct Event
{
int i;
};
class EventManager
{
public:
void subscribe(std::string const& eventName,
std::function<void(Event const&)> event)
{
abc.push_back(event);
}
static EventManager& get()
{
static EventManager instance;
return instance;
}
void onEvent(Event const& event)
{
for (auto&& f : abc)
{
f(event);
}
}
private:
EventManager() {}
EventManager(EventManager const&) = delete;
EventManager& operator=(EventManager const&) = delete;
std::vector<std::function<void(Event const&)>> abc;
};
struct ATideManager
{
void f()
{
EventManager::get().subscribe("EventName",
[=](Event const& event) { eventTest(event); });
}
void eventTest(Event const& event)
{
std::cout << "eventTest: " << event.i << "\n";
}
};
int main()
{
ATideManager manager;
manager.f();
Event some_event{ 123 };
EventManager::get().onEvent(some_event);
}
I've also fixed your needless use of pointers where references can be used, and some const-correctness issues.

obj->*newEvent is invalid. A member function pointer can be used in this way only to call the pointed-to member function.
You can however use std::vector<std::function<void(Event)>> and
abc.push_back(std::bind(newEvent, obj, std::placeholders::_1);
std::bind reference

Related

Vector of pointer to member functions

I'm trying to write a program which creates a class that contains vector of pointers to member functions, with add() and remove() member functions.
The code I wrote is -
#include <iostream>
#include <vector>
using namespace std;
typedef void(*classFuncPtr)();
class FunctionVectors
{
private:
vector<classFuncPtr> FunctionPointerVector;
public:
FunctionVectors(){}
void add(classFuncPtr funcPtr);
void remove(int index);
void run();
void a(){cout<<"a: Why are you calling me?"<<endl;}
};
void FunctionVectors::add(classFuncPtr funcPtr)
{
FunctionPointerVector.push_back(funcPtr);
}
void FunctionVectors::remove(int index)
{
FunctionPointerVector.erase(FunctionPointerVector.begin() + index);
}
int main()
{
FunctionVectors f;
classFuncPtr fv = &(classFuncPtr)FunctionVectors::a; // error here
f.add(fv);
f.run();
return 0;
}
But, it is showing error in line# 32 -
error C2440: 'type cast' : cannot convert from 'void (__thiscall FunctionVectors::* )(void)' to 'classFuncPtr'
Please, tell me how should I modify it to work properly.
typedef void(*classFuncPtr)();
This is not a pointer to method, but a pointer to function. Method differs from function, because it's being called in a context: requires this to work correctly.
Keep in mind, that in C++ you are only able to create vector of pointers to a method of specific class. So you won't be able to keep pointers to two methods of different classes in that vector.
The solution - as suggested in comments - is to use std::function or boost::function and possibly C++11 lambdas, because they provide a lot more flexibility than simple pointer-to-members.
If you want to implement an event mechanism, consider also using functors instead of methods:
Create base class for event handler:
class MyEventHandler
{
public:
virtual void operator()(void * sender, int data) = 0;
}
Create simple vector of these:
std::vector<MyEventHandler *> MyEvent;
Create specific handlers in your classes:
class MyClass
{
private:
class SpecificEventHandler : MyEventHandler
{
public:
void operator()(void * sender, int data)
{
std::cout << "Event handled!";
}
}
public:
SpecificEventHandler Handler;
MyClass()
{
}
}
Hook the handler to your event:
MyEvent.push_back(&(myClassInstance.Handler));
Code written from memory, may not compile, but you should get the idea.
std::function< void() >
looks like the signature you are looking for. If it isn't available in your version of C++ but you can use boost, then you fill find it in boost. Look up documentation for appropriate header, for std, for function.
To create one for a member function, you need to bind it, and to bind it to FunctionVectors::a() you will need an instance of a FunctionVectors to call it on.
In your example, I will make the typedef for you
typedef std::function< void() > classFuncPtr; // in reality a badly named typedef
int main()
{
FunctionVectors f;
classFuncPtr fv = std::bind( &FunctionVectors::a, f );
}
alternatively if you really have C++11 with lambdas you can do
classFuncPtr = [ f ]() { f.a() );
In your case I reckon you don't really want a free function, you always want a member function of your class you want.
typedef void (*FunctionVectors::classFuncPtr )();
and you would use
(this->*func)();
to invoke it

Best practice for local variable scope in a C++ callback

I have a functioning C++ callback function, triggered by a user 'mouse down' event. (The IDE is VS2010.)
With each call, I'd like to increment a simple count variable that is local to the callback's scope. Simply put, what is the 'best practices' way to do this?
Thanks in advance for any opinions or directives.
Replace your callback function with a functor - they can store state. An example functor:
#include <iostream>
#include <memory>
class Functor
{
private:
std::shared_ptr<int> m_count;
public:
Functor()
: m_count(new int(0))
{}
void operator()()
{
++(*m_count);
// do other stuff...
}
int count() const
{
return *m_count;
}
};
template <typename F>
void f(F callback)
{
// do stuff
callback();
// do other stuff
}
int main()
{
Functor callback;
f(callback);
f(callback);
std::cout << callback.count(); // prints 2
return 0;
}
Note the use of a shared_ptr inside the functor - this is because f has a local copy of the functor (note the pass-by-value) and you want that copy to share its int with the functor to which you have access. Note also that f has to take its argument by value, since you want to support all callables, and not just functors.

functors + member pointers to create signal object

I have this code:
// signal supporter parent
class signalable {};
template <class typeT = signalable>
typedef void (typeT::*trig)(std::string);
template <class typeT = signalable>
class trigger
{
private:
typeT* instance;
typeT::trig fun;
public:
trigger(typeT* inst, typeT::trig function)
: instance(inst), fun(function)
{}
void operator ()(std::string param)
{
(instance->*fun)(param);
}
};
And I get lots of compile error that I bet pros know of. I'm just confused a little bit about this context.
What I want to do is clear: Pass pointer to an object, and pointer to one of it's member functions, to make a functor and pass it over in my program.
Would appreciate your helps and "corrections".
Thank you!
Are you trying to do something like this?
#include <string>
#include <iostream>
// signal supporter parent
class signalable
{
public:
void foo(std::string s) { std::cout << "hello: " << s << std::endl; }
};
template <class typeT = signalable>
class trigger
{
typedef void (typeT::*trig)(std::string);
private:
typeT* instance;
trig fun;
public:
trigger(typeT* inst, trig function)
: instance(inst), fun(function)
{}
void operator ()(std::string param)
{
(instance->*fun)(param);
}
};
int main()
{
signalable s;
trigger<> t(&s, &signalable::foo);
t("world");
}
As for some of the more specific errors in your code, most of them seem to relate to your typedef. C++11 allows "template typedefs", but they don't look like that. Have a look at this thread for an example of template typedefs:
C++ template typedef

What is the best way to expose a callback API - C++

I have a C++ library that should expose some system\ resource calls as callbacks from the linked application. For example: the interfacing application (which uses this library) can send socket management callback functions - send, receive, open, close etc., and the library will use this implementation in stead of the library's implementation.
(This way enables the application to manage the sockets by itself, can be useful).
This library has to expose also more callbacks, like, for example, a password validation, so I wonder if there is a preferred method to expose the callback sending option in one API.
Something like:
int AddCallbackFunc (int functionCallbackType, <generic function prototype>, <generic way to pass some additional arguments>)
Then within my library I will assign the callback to the appropriate function pointer according to the functionCallbackType parameter.
Is there any way to implement it in a generic way which will fit ANY function prototype and ANY additional arguments?
Your help will be more than appreciated...
Thanks!
Why not have it accept a 0 argument functor and just have the user use boost::bind to build the arguments into it before registering it? Basically example (calls instead of stores, but you get the point):
#include <tr1/functional>
#include <iostream>
void callback(const std::tr1::function<int()> &f) {
f();
}
int x() {
std::cout << "x" << std::endl;
return 0;
}
int y(int n) {
std::cout << "y = " << n << std::endl;
return 0;
}
int main(int argc, char *argv[]) {
callback(x);
callback(std::tr1::bind(y, 5));
}
EDIT: There is an option B, which is to basically implement what bind does under the hood with structures to store all the needed info and inheritance for polymorphism... it becomes a mess real quick. I would not recommend it, but it will work. You can also save from grief by forcing a return type of int, but that only saves you a little.
#include <iostream>
struct func_base {
virtual int operator()() = 0;
};
// make one of these for each arity function you want to support (boost does this up to 50 for you :-P
struct func0 : public func_base {
typedef int (*fptr_t)();
func0(fptr_t f) : fptr(f) {
}
virtual int operator()() { return fptr(); }
fptr_t fptr;
};
// demonstrates an arity of 1, templated so it can take any type of parameter
template <class T1>
struct func1 : public func_base {
typedef int (*fptr_t)(T1);
func1(fptr_t f, T1 a) : fptr(f), a1(a) {
}
virtual int operator()() { return fptr(a1); }
fptr_t fptr;
T1 a1;
};
void callback(func_base *f) {
(*f)();
}
int x() {
std::cout << "x" << std::endl;
return 0;
}
int y(int n) {
std::cout << "y = " << n << std::endl;
return 0;
}
int main(int argc, char *argv[]) {
// NOTE: memory leak here...
callback(new func0(x));
callback(new func1<int>(y, 5));
}
If you don't want to go for any of the C++ options available; std::tr1::function, functors, polymorphism with common base class etc. you can use the C method instead.
The client passes a callback and a pointer to its arguments as a void*, then the callback casts the void* to the correct type when it's called. You'll need to store the void* alongside the callback and you'll need to be very careful with object lifetimes.
int AddCallbackFunc (int type, int(*callback)(void*), void* callbackData)
It can be done, using a combination of template and type-erasure.
The idea is to take any type and wrap it into an object with a known interface.
class CallbackBase
{
public:
virtual ~CallbackBase();
virtual void execute();
};
template <class T>
class Callback: public CallbackBase
{
public:
explicit Callback(T functor): mFunctor(functor) {}
void execute() { mFunctor(); }
private:
T mFunctor;
};
And now, we can wrap it:
template <class Function>
int AddCallbackFunc (int functionCallbackType, Function f)
{
std::auto_ptr<CallbackBase> c(new Callback<Function>(f));
// do something with `c`.
}
I leave it up to you to bind the arguments, the no library way is to create a functor.
Sounds like you're looking for a Functor. Basically a class for each type of callback, with the arguments as data members and operator() to invoke the functionality.

Map of boost function of different types?

i was wondering if there was a way to do this in C++?
void func1(const std::string& s)
{
std::cout << s << std::endl;
}
void func2(int me)
{
std::cout << me << std::endl;
}
int main()
{
std::map<std::string, boost::function< ??? > > a_map;
a_map["func1"] = &func1;
a_map["func1"]("HELLO");
}
Is there any way to do what i have above using boost function and a map?
There are ways to store the functions, the problem is, in order to be able to call the function with the desired argument you'd have to know the calling signature of the function anyways, and if you have that information, you might as well use separate maps, or use a more complicated object than boost::function.
If you're willing to do a bit of work and have a finite number of signatures, you could just do something like this:
class MultiFunc
{
protected:
MultiFunc() {}
public:
typedef void (*stringFunc)(const std::string&);
typedef void (*intFunc)(int);
static MultiFunc *Create(stringFunc function);
static MultiFunc *Create(intFunc function);
virtual void operator()(const string &) { throw exception(); }
virtual void operator()(int) { throw exception(); }
virtual ~MultiFunc();
};
class MultiFuncString : public MultiFunc
{
private:
stringFunc Function;
public:
MultiFuncString(stringFunc function) : Function(function) {}
virtual void operator()(const string &arg) { Function(arg); }
};
class MultiFuncInt : public MultiFunc
{
private:
intFunc Function;
public:
MultiFuncInt(intFunc function) : Function(function) {}
virtual void operator()(int arg) { Function(arg); }
};
MultiFunc *MultiFunc::Create(MultiFunc::stringFunc function)
{
return new MultiFuncString(function);
}
MultiFunc *MultiFunc::Create(MultiFunc::intFunc function)
{
return new MultiFuncInt(function);
}
void func1(const std::string& s)
{
std::cout << s << std::endl;
}
void func2(int me)
{
std::cout << me << std::endl;
}
int main()
{
map<string, MultiFunc *> a_map;
a_map["func1"] = MultiFunc::Create(&func1);
(*a_map["func1"])("Hello");
a_map["func2"] = MultiFunc::Create(&func2);
(*a_map["func2"])(3);
// Remember to delete the MultiFunc object, or use smart pointers.
}
This outputs:
Hello
3
Unfortunately, you can't make templated virtual functions or you easily generalize this all.
You probably can't use the std::map since it is a homogenous container. Try, something like boost::variant (they support the visitor pattern) or boost::tuple
What you are trying to do sounds a little weird. Normally, you would have a container be a collection of abstract types or objects or functions with the same signature. Otherwise, how would you know how to call the function when you are iterating the container? I like to make the container a collection of function objects with a known signature, then use Boost.Bind to store closures that call the function with additional arguments.
For example:
typedef boost::function<void, void> Function;
typedef std::map<std::string, Function> Functions;
Functions functions:
void foo()
{
...
}
functions["foo"] = foo;
void bar(std::string &s)
{
...
}
// binds the value "hello" to the s parameter
functions["bar"] = boost::bind(bar, "hello");
read this link below. It talks about using boost::bind to store the function pointers in std::map
http://www.gamedev.net/community/forums/topic.asp?topic_id=526381&whichpage=1&#3411515
store interfaces:
struct IStringData
{
virtual std::string get() const = 0;
virtual ~IStringData() {}
};
and make implementaions, one will just hold string value, other implementation will store functor, maybe you will have other implementations in future.
No. You can't. Since boost::function isn't polymorphic, it breaks down there. (It takes a fixed set of argument types.)
There was talk about work in that direction on the boost mail-list, though, so search the archives and see if there is some code you could youse.
A workaround would be to use boost::function but then you need to add to the map not your real functions (i.e. func1/func2) but dispatch functions that extracts the type from the any-container and calls the real function. (And bails if it's wrong, just as in any dynamic langugage.)