In c++ is there any Events/delegates/interfaces/notifications! anything? - c++

Say i have these classes
ViewA and ViewB
In objective C using the delegate pattern I could do
#protocol ViewBDelegate{
- (void) doSomething();
}
then in ViewB interface:
id<ViewBDelegate> delegate;
then in ViewA implementation i set the delegate:
viewB.delegate = self;
and now I can call in doSomething from viewB onto any that unknown type delegate.
[delegate doSomething];
"C++ How to Program" has been the worse read an can't find simple examples that demonstrates basic design patterns.
What i'm looking for in C++ is:
events ActionScript and java
or delegates or NSNotifications in Objective C
anything that allows class A, Class B and Class C to know that ClassX
didSomething()!!!
thanks

If I were you, I wouldn't use function pointers to accomplish this task. Leave this option to the gurus ;)
In Boost, there is a beautiful library called signals. It makes your life easier! This is an example of usage:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/signal.hpp>
using namespace std;
using namespace boost;
struct A
{ void A_action() { cout << "A::A_action();" << endl; } };
struct B
{ void B_action() { cout << "B::B_action();" << endl; } };
struct C
{ void C_action() { cout << "C::C_action();" << endl; } };
struct X
{
// Put all the functions you want to notify!
signal<void()> list_of_actions;
void do_something()
{
std::cout << "Hello I am X!" << endl;
list_of_actions(); // send notifications to all functions in the list!
}
};
int main()
{
X x;
A a;
B b;
C c;
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
x.do_something();
}
This will print:
Hello I am X!
A::A_action();
B::B_action();
C::C_action();
Here is how it works.
First, you declare the place that holds the delegates:
signal<void()> list_of_actions;
Then, you "connect" it to what ever group of functions/functors/callable things you want to call.
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
Note, that I have used bind. So, that the type of functions in the list_of_actions is the same, but we can connect it to different type of classes. So:
bind(&A::A_action, a)
This thing, produces a callable thing, of type void () as we declared the type of list_of actions earlier. Of course, you specify the instance you want to apply this member function on in the second parameter..
If you are doing multi-threaded stuff, then use its sister signals2.
Hope that helps.

anything that allows class A, Class B
and Class C to know that ClassX
didSomething()!!!
Probably you are looking for signals & slots, which has multiple implementations:
Boost
Qt
I'm sure there are more, but these are the most significant of which I'm aware.

There are no delegates/events/etc.
You can simulate interfaces using pure virtual function, see here for a similar question.
And there are the function pointers...
So basically the answer to you question is no, there are none of that in C++ (don't know about the latest standard), but there are substitutes and workarounds..

Personally I like The Impossibly Fast C++ Delegates by Sergey Ryazanov. Very neat and easy to use implementation, claimed to be faster than Boost::function.
You can find events implemented there, too. I don't use them, however. I implemented my own event handling using .NET style (sender, args).

Neither the C++ language, nor its associated Standard Library, either have delegates or events. There are of course many libraries that implement such things, or you can implement them yourself.

All i know there is a type of method called call-back method(In fact, function pointer).
Delegation? It's just a kind of wrapped call-back method, and, looks advanced

"C++ How to Program" has been the worse read an can't find simple examples that demonstrates basic design patterns
I think that the original Design Patterns book includes examples of how to implement each pattern using C++.

Related

macro that defines entire derived class from one function and certain type specifiers?

I have a class called system. A system takes some object managers and changes all objects in them in some way.
For example there might be a system that draws all images in a imageManager.
Every derived class works somewhat like this (pseudo code):
class someChildClass : public System{
private:
someObjectManager &mang1; //these are used by the update method.
someOtherObjectManager &mang2;//the update method changes these somehow
public:
someChildClass(someObjectManager &mang1, someObjectManager &mang2)
:mang1(mang1),mang2(mang2){
}
virtual void update(){
//this is pure virtual in the System base class.
//Do something with the managers here
}
}
I feel like writing everything but the update method is a waste of time and a source of errors. I wanted to write a macro that basically makes a class like this like so:
QUICKSYSTEM(thisIsTheSystemName, someObjectManager, mang1, someOtherObjectManager, mang2, ... (infinite possible Managers. So a variadic macro?)){
//this is the update function
}
}//this is the end braked for the class declaration. Its ugly but I dont know how I could do the function differently?
well I am having some problems making the macro. Everything works fine until I need to split the variadic arguments into the names and the types. I dont know if this is even possible now, since I cant go back and forth in the arguments easily or apply a easy step to them to make sure that every 2nd is the name of the variable. I would be ok with omitting the possibility for names and just had the types with some sort of automatic naming (manager1,manager2,manager3 or something like that).
If this isnt possible using a macro, what would be a better way to avoid mistakes and cut some time in the constructor and class declaration part?
Yeah, macros are really, really not the way to do this. C++ has templates, which follow C++ syntax and support C++ expressions. Macros instead use their own preprocessor language, which is almost entirely unaware of C++.
You'll want to read up a bit on std::tuple as well. It's going to be rather tricky to handle all those managers with those names. Tuples are the Standard solution for that. managers.get<0> and managers.get<someObjectManager> both work.
Variadic templates are the tool you need here:
#include <iostream>
#include <tuple>
#include <functional>
struct System { void virtual update() = 0; };
template<class... Managers>
struct ManagedSystem : System
{
std::function<void(Managers&...)> _update;
std::tuple<Managers&...> _managers;
template<class F>
ManagedSystem(F update, Managers&... managers) : _update(update), _managers(managers...) {}
void update() override { _update(std::get<Managers&>(_managers)...); }
};
int main()
{
int n = 0;
double d = 3.14;
auto reset = [](int& a, double& d) { a = 0; d = 0.0; };
ManagedSystem<int, double> ms{reset, n, d};
ms.update();
std::cout << "n = " << n << ", d = " << d << "\n";
// n = 0, d = 0
}
The idea is to define a templated-class (ManagedSystem) taking as template-parameters multiple manager types. This class inherits from Systemand provides a constructor taking:
an update functor,
and references to manager whose type is defined by the template parameters of the class.
The said managers are registered internally in an std::tuple and (with a bit of parameter pack magic fed to the update functor.
From there, you can define an inherited class from System by providing an update function and a type list. This avoids the use of ugly and type-unsafe macros in favor of the not-less ugly but type-string templates ;)

Use templates to clone class types exactly?

I have a series of C++ classes that I wish to all be identical in functionality, but otherwise not related by inheritance. Effectively, these classes would differ in name only. (These classes will be thrown, and I do not want a catch clause for some base class to gobble up thrown derived objects. There will be derived classes, but I wish to create discrete sets of thrown classes that are always segregated, as far as catch blocks are concerned.)
Of course, the downside to this is duplicating source code. I don't want to have to update N copies of the same code, whenever something needs to be changed.
I have already solved the code duplication problem via #define. But I think it would aid debug-ability if I could leverage templates, instead. The only thing parameterized in the template will be the class name itself.
I attempted the following, which did not work in gcc (w/ c++0x support enabled):
template<typename ClassName>
class ClassName
{
public:
ClassName(int foo, float bar) { ... }
~ClassName() { ... }
bool SomePublicMethod() { ... }
private:
...
}
Then I would declare the actual classes with something akin to:
typedef ClassName<UnrelatedClass1> UnrelatedClass1;
typedef ClassName<UnrelatedClass2> UnrelatedClass2;
I already know that the above does not work; I am providing it as a conceptual example of what I would like to accomplish, and am wondering if there is a way to make it work, other than the #define macro method that I am presently using (which suffers from diminished debug-ability.)
Use value specialized template:
template<int ID>
class ClassName
{
public:
ClassName(int foo, float bar) { ... }
~ClassName() { ... }
bool SomePublicMethod() { ... }
private:
...
}
typedef ClassName<1> UnrelatedClass1;
typedef ClassName<2> UnrelatedClass2;
This doesn't sound like a very good idea at all.
Exceptions classes should capture a specific type of error, with inheritance used to more generalise the type of error.
So for example you might have a 'disk crashed exception', which more generally might be a 'disk exception' and more generally and 'io exception' and always at its core an 'std::exception'
If all your exceptions are catching different types/classes of error, then why would they all have the same type of implementation.
Also it's uncommon to see #define mixed in the templates because that invariably makes it less readable when there is a compiler error (even if it seems more readable when it is no causing errors).
Perhaps you could provide more information about what is implemented in your exception classes, and I can see if I can help you further.
I do agree with others when they say that you should use inheritance. It is great for many purposes (one of them being the reason why you would like to have similar classes). It is not compulsory to write derived classes only when the objects are related - it is great even if just the functionality that is matching because your idea really is to put similar code together.
However, since your query was about creating multiple classes and we do not have enough view of your project, I believe it is possible that you may really need separate classes. One way of doing this is through macros. Here's a sample:
#include <iostream>
using std::cout;
using std::endl;
#define CUSTOM_CLASS(_CL) class _CL\
{\
public:\
_CL(int foo, float bar) { cout << "Creating instance with foo=" << foo << ";bar=" << bar << endl;}\
~_CL() { }\
bool SomePublicMethod() { cout << "Class created\n"; }\
};
CUSTOM_CLASS(myclass1);
CUSTOM_CLASS(myclass2);
int main()
{
myclass1 instance1(1, 1.3f);
myclass2 instance2(2, 0.3f);
return 0;
}
If you run this using g++, you will get the following result:
Creating instance with foo=1;bar=1.3
Creating instance with foo=2;bar=0.3

C++ Function pointers vs Subclasses

I am in a position to choose between function pointers and subclassed objects. To make it clear, say I have to notify some object of some action (a timer for example); refer to the following two choices (a very basic code for demo purposes):
Version 1
typedef void TimerCallback(void *args);
class Timer{
public:
Timer();
~Timer();
void schedule(TimerCallback *callback, void *args, long timeout)=0;
void cancel();
};
Version 2
class TimerTask{
public:
TimerTask();
virtual ~TimerTask();
void timedout()=0;
};
class Timer{
public:
Timer();
virtual ~Timer();
void schedule(TimerTask *callback, long timeout)=0;
void cancel();
};
which one is the standard C++ way and which one is efficient? Please let me know if you have any other suggestions in this regard.
Please let me know if I am not clear in this regard.
Thanks
I would say std::function and std::bind. Then it doesn't matter if you want to use inherited classes, standalone functions, member functions or lambdas.
By the way, if anyone is curious I made a simple timer event handling some time ago, as an answer to another question. It's showcasing the use of e.g. std::function and std::bind: https://stackoverflow.com/a/11866539/440558.
I think it's better to use boost(or std since C++11)::function to hold callback and boost::bind to bind it's arguments, or to use boost::signal.
That would be more general and verbose solution at cost of really small penalty.
http://www.boost.org/doc/libs/1_53_0/doc/html/signals2.html
You are using object-oriented programming and you should follow the object-oriented programming paradigms.
In my opinion using objects, not function pointers, is the cleaner and generally better way to do.
You can also attempt to use a visitor pattern to make the code even better and more flexible.
You can also consider publisher/subscriber pattern.
Function pointer effectively prevents you to use closures - assigning methods to you event handler (This is not entirely true, but it will restrict you in such way, that this solution is not much of a use).
I would vote on object-oriented approach. If you use C++11, you may simplify your code a lot:
#include <cstdio>
#include <functional>
class Emitter
{
private:
std::function<void(int)> eventHandler;
public:
void SetEventHandler(std::function<void(int)> newEventHandler)
{
eventHandler = newEventHandler;
}
void EmitEvent()
{
eventHandler(42); // + error-checking
}
};
class Handler
{
private:
void HandleEvent(int i)
{
printf("Event handled with i == %d\n", i);
}
public:
void AttachEmitter(Emitter & e)
{
e.SetEventHandler([this](int i) { HandleEvent(i); });
}
};
int main(int argc, char * argv[])
{
Emitter e;
Handler h;
h.AttachEmitter(e);
e.EmitEvent();
}
Both work. Your first one is "C style" and will require a static function somewhere. The second version is "C++ style" and allows you to use an instance of TimerTask.
Generally, version 2 should be used because it removes the need for a static function.

Can I use templates/macros/both to wrap each function of a C++ class?

Suppose I had this.
class A {
public:
int f1();
int f2();
}
Is there any way to use templates/macros/both to generate a class that behaves like the following?
class GeneratedClass {
public:
GeneratedClass(InjectedFunction injected_function) { /* store it */ }
int f1() {
injected_function();
/* forward call to "inner class" and return its value */
}
int f2() {
injected_function()
/* forward call to "inner class" and return its value */
}
}
Basically I want to be able to generate a class that supports all the functions of a given class, but doing something before it blindly forwards the call.
This class will be created with something like.
SomeClassTemplate<A> infected_a(injected_function);
No, templates cannot generate that code for you automatically. You must write it by hand.
It sounds like you want aspect-oriented C++. This link discusses implementing aspect-oriented C++ with pure C++ and also with a language extension.
See also here for an implementation.
Aspect-oriented programming is about separation of concerns in a project. Insertion points are specified where code is inserted. Sounds like exactly what you want.

Passing a C++ method to an Objective-C method

I have a C++ class 'Expression' with a method I'd like to use in my Objective-C class 'GraphVC'.
class Expression {
double evaluate(double);
}
And my Objective-C class:
#implementation GraphVC : UIViewController {
- (void)plot:(double(*)(double))f;
#end
I thought that it would be easiest to pass around function pointers that take a double and return a double, as opposed to C++ objects, but I haven't had much success using functional.h. What's the best way to use my C++ method from Objective-C?
EDIT: Thanks for your quick responses. Allow me to elaborate a bit... I have a backend written in C++ where I manipulate objects of type Expression. There's subclasses for rational, polynomial, monomial, etc. My initial idea was to use mem_fun from , but I wasn't able to get code compiling this way. I also had trouble using bind1st to bind the this pointer.
Writing an Objective-C wrapper is a possibility, but I'd rather use the already existing evaluate() function, and I don't want to break the clean separation between the backend and the iPhone GUI classes.
I can't have a global expression or use a static method (I need to plot arbitrary Expression instances.
I should have more explicitly stated that I need to pass a C++ member function (not a static function or existing C function) to an Objective-C object. Has anyone had luck using C++'s <functional> to turn member functions into pointers I can use in an Objective-C object, or should I use an Objective-C wrapper?
If you want to make a pointer to a method in C++, you need to include the class name, like this:
class Foo
{
public:
double bar(double d)
{
return d;
}
};
void call_using_obj_and_method(Foo *f, double (Foo::*m)(double d))
{
(f->*m)(3.0);
}
int main()
{
Foo f;
call_using_obj_and_method(&f, &Foo::bar);
return 0;
}
Note that you need an instance of the class as well. In my example this is another parameter, though you could let it be a global variable, or a singleton instance of class Foo.
Though, like jkp said, you can also solve the problem by making the method static or turning it into a regular function.
EDIT: I'm not sure if I understand your question correctly. I don't think you need to use functional. Here is how my example would look in Objective-C++:
#include <Cocoa/Cocoa.h>
class Foo
{
public:
double bar(double d)
{
return d;
}
};
typedef double (Foo::*fooMethodPtr)(double d);
#interface Baz : NSObject
{
}
- (void)callFooObj:(Foo *)f method:(fooMethodPtr)m;
#end
#implementation Baz
- (void)callFooObj:(Foo *)f method:(fooMethodPtr)m
{
(f->*m)(3.0);
}
#end
int main()
{
Foo f;
Baz *b = [[Baz alloc] init];
[b callFooObj:&f method:&Foo::bar];
return 0;
}
I would suggest wrapping the C++ class in an Objective-C class, and then also providing a
- (void) plotWithObject:(id)obj
{
double result = [obj evaluate: 1.5];
// ... etc ...
}
in addition to the plot: method.
I think the problem here is that you are trying to pass a member function of your Expression class to the Objective-C class. This will not work because it's expecting a this pointer as the first argument to that function (therefore the signature is not the same as the one expected by the plot: method.
If you make the C++ method a static, you can do this, but then you don't buy yourself a lot over using a standard C function.
IE, if the Expression class looked like this:
class Expression {
static double evaluate(double);
}
You should be able to call it like this:
[self plot:myExpression.evaluate(&Express::evalulate)];
As I say though, there isn't a huge amount of value in this because you may as well be using a standard C function (unless you can do something in the C++ class that is more useful to you).
I did once look at trying to bridge boost::bind() results with objective-c methods but didn't get very far. I'm sure if you dig deep enough in the C++ runtime you could do it though.
If your C++ member function returns a double, can't your code just look like this?
- (void)plot:(double)f;
...
[self plot:myExpression.evaluate(aDouble)];
Or something similar. I've not used much mixing of Obj-C and C++, but this is how I would approach it. You also might have to have a .mm extension on your Objective-C++ file if you're mixing them like that.
Why wouldn't you pass the instantiated c++ class around inside an NSValue and then call the c++ method directly?
- (NSValue*)getExpression
{
Expression* e = new Expression();
return [[NSValue alloc] initWithPointer:e];
}
- (void)callExpression(NSValue*)expression
{
Expression* e = [expression pointerValue];
e->evaluate();
}