I am making a small tower defence game in order to practice C++. I know other languages, but have done little actual development in C++.
In this game I'll have several buildings, so I made a class like so:
class Building
{
private:
sf::Sprite& sprite;
float timer = 0;
void update(float delta);
};
Now, I'll have many different buildings, but they should all have the same members. Now, in Java I would (have to) make a subclass for each different type of building, bu I was thinking, can I change void update(float delta); to std::function<void(float)> update; and have factory funtions to create the different buildings? What I imagine is something like this:
In building.h:
class Building
{
private:
sf::Sprite& sprite;
float timer = 0;
std::function<void(float)> update;
};
And in building.cpp
Building getBuildingA()
{
Building b;
b.sprite = /* ... */
b.update = [](float delta) {
std::cout << timer++ << std::endl;
};
return b;
}
But of course, I cannot actually access the variable timer there. Is there a way I can do something similar?
You can make the lambda capture this. A better solution is probably something like
class Building
{
private:
sf::Sprite& sprite;
float timer = 0;
std::function<void(Building*, float)> update_impl;
void update(float x) { update_impl(this, x); }
};
But really, based on this fragment of your design it looks like you really should be using subclasses and virtual functions; this is the sort of thing they're meant for.
The typical application of function is when you pass function objects around -- e.g. to replace the Java paradigm of writing an interface class with a single method, especially in settings when you'd rather just write functions or lambdas rather than whole objects.
For object polymorphism, the main alternative to subclassing and virtual functions is to use templates and generic programming -- although that's mainly for when you need polymorphism to happen at compile time. (which, I imagine, is inappropriate for your circumstance)
You can simply capture this.
As an example:
struct S {
auto foo() {
return [this](){ this->bar(); };
}
void bar() { }
};
int main() {
S s;
s.foo()();
}
If you are using C++14, you can use an initializer list instead.
As an example:
#include<cassert>
struct S {
auto foo() {
return [timer = timer](){
assert(timer == 42);
};
}
int timer{42};
};
int main() {
S s{};
s.foo()();
}
This way, you'll get a copy-initialized variable named timer to be used within the body of the lambda function.
You can work around the privacy issue by using a static-member function of Building to provide the factory class.
A secondary issue you're going to run into is that you're returning a Building by value, so, unless RVO happens you won't know the ultimate address of the object you are returning. You can work around this by having your "update()" function pass it's "this" as a parameter.
#include <iostream>
#include <functional>
class Building {
// C++ classes are private by default
int timer_;
std::function<void(Building*)> update_;
public:
void update() {
update_(this);
}
static Building getBuildingA() {
Building b;
b.timer_ = 42;
b.update_ = [](Building* b) {
b->timer_++;
std::cout << b->timer_ << '\n';
};
}
};
int main() {
Building b = Building::getBuildingA();
b.update();
return 0;
}
Working demo: http://ideone.com/1Jy6zI
But also be aware that you cannot assign a reference to initialize it, you must initialize it. Also be aware that C++ is not ref-counted by default, so your reference to the sprite can easily become a dangling reference.
You might want to consider a std::shared_ptr instead of a reference.
Related
I am working on translating some Java code to C++.
In Java, we can create object from anonymous class, using existing constructor, and overriding some methods. E.g.,
class X {
public X(int value) {...}
public void work() {....}
}
void main(String[] args) {
X entity = new X(5) {
public void work() { /* Something else */ }
};
}
In C++, I know I can create anonymous class as following:
class X {
public:
virtual void work() {...}
}
class : public X {
public:
void work() {....}
} obj;
But C++ does not allow constructor in anonymous class, and it does not allow extending from object (e.g., the new X(5) { public void work() {} } like what Java allows.
How can I write similar code in C++?
Update 03/07/2020 05:27 CDT
More context about the problem I am working on. I am implementing aggregation function of a in-memory SQL database, and use the following class to represent an aggregation field:
class AggField {
public:
AggField(int colIndex);
virtual void reduce(DataRow&) = 0;
virtual double output() = 0;
}
For each type of aggregation, e.g., avg, min/max and sum, I have a subclass. For example
class Avg : public AggField {
private:
int counter_;
double value_;
public:
Avg(int colIndex) : AggField(colIndex), counter_(0), value_(0) {};
void reduce(DataRow&) override {
value_ += row[colIndex].doubleval();
counter_ += 1;
}
double output() override {
return value_ / counter_;
}
}
class Sum : public AggField {
.....
}
When processing a table, I will write the following
Table table = ...
auto agg_opr = Agg({
new Sum(0),
new Avg(1)
});
agg_opr.agg(table);
which does a sum on column 0, and average on column 1.
Sometimes(rare) I need to process more than one input columns. For example, doing a sum of col1 * (1 + col2). Instead of creating a new subclass of AggField, I would like to write something similar to:
Table table = ...
auto agg_opr = Agg({
new Sum(0) {
void reduce(DataRow& row) {
value_ += row[0].doubleval() * (1 + row[1].doubleval());
}
},
new Avg(1),
new Max(1)
});
agg_opr.agg(table);
I can't say that I know how to write idiomatic Java but I'm guessing that this pattern in Java is an alternative to lambdas in C++. I remember using an anonymous class long ago when I was working with Swing. I think I did something like this:
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// ...
}
});
This is sugar for inheriting from a class and overriding a method. Doing precisely that is not really how I would like to attach an event listener in C++. I'd prefer to do this:
button.addMouseClickListener([](const MouseEvent &e) {
// ...
});
In the case of an event listener, the closure would need to be stored in a std::function or something similar. This has roughly the same performance as a virtual call.
I don't really know much about where you're using this class but if you need to store it aside (like an event listener or something) then declaring the class the long way or using std::function are probably the cleanest options. If you don't need to store it aside (like a policy for an algorithm) then you could use a functor. Of course, you can store aside a functor but it takes a bit of template machinery and probably isn't worth it (although it does have more flexibility).
struct MyPolicy {
int doSomething(int i) {
return i * 3;
}
double getSomething() const {
return d;
}
double d;
};
template <typename Policy>
void algorithm(Policy policy) {
// use policy.doSomething and policy.getSomething...
}
Using a functor or lambda with a template has much better performance than using virtual functions. In the above example, the compiler can and probably will inline the calls to doSomething and getSomething. This isn't possible with virtual functions.
If I knew more about the real problem that you're trying to solve then I might be able to write a more specific and helpful answer.
After seeing the updated question I have another suggestion. That would be to create a subclass for custom aggregate functions. Of course, this has plenty of limitations.
template <typename Func>
class CustomAgg : public AggField {
public:
CustomAgg(int colIndex, Func func)
: AggField{colIndex}, func{func} {}
void reduce(DataRow &row) override {
func(value, row);
}
double output() override {
return value;
}
private:
Func func;
double value = 0.0;
// could add a `count` member if you want
};
auto agg_opr = Agg({
new CustomAgg{0, [](double &value, DataRow &row) {
value += row[0].doubleval() * (1 + row[1].doubleval());
}},
new Avg(1),
new Max(1)
});
Honestly, I think the best solution for you is to not try to implement a Java feature in C++. I mean, if you need to handle multiple columns in some specific operation then create a class just for that. Don't take any shortcuts. Give it a name even though you might only use it in one place.
C++ has anonymous namespaces, which effectively lets you create classes that are completely isolated to the translation units they're declared in:
namespace {
class X {
public:
X(int) { /* ... */ } // Ok to have a constructor
void work();
};
}
int main(int argc, char **argv)
{
X entity{5};
// ...
}
Now, you have to declare them in global scope, you can't declare them in inner scope. You'll also need to give these classes normal names that you can reference them by in the same translation unit; but for all practical purposes they're completely anonymous and inaccessible from other translation units. Another translation unit can declare its own anonymous class "X", and there won't be any conflicts.
You can use anonymous classes in all other normal ways, subclass them, etc... You can create an anonymous class that's a subclass of a regular, non-anonymous class, which gets you pretty close to what Java does, here.
Some compilers also offer extensions where you can declare classes in inner scopes, and they'll also work very similar to anonymous namespaces, but that's going to be a compiler-specific extension.
I'm currently working on a piece of code in C++11:
class A {
public:
//.. generic public methods which call updateInternalState from time to time ..
private:
void updateInternalState();
B internalState;
};
Now I want to have several versions of class A which are all identical except for the updateInternalState() method, which is to vary and has atleast 3 different versions, doing different things and might have even more in the future. This sounds almost like a good place to use inheritance with a base class, but I'm wondering if there is a template-metaprogramming version for this, e.g.:
#include <functional>
template <std::function<void()> updateInternalState>
class A {
public:
//.. generic public methods, which call updateInternalState from time to time ..
private:
B internalState;
Then I would only have to define the functions somewhere else and explicitly instantiate the versions of A that I want.
I think the biggest problem is that the updateInternalState function needs access to the private members of A. I'm thinking this could be solved by declaring it as a friend of A, or by storing a member of type std::function and assigning the the template argument to it.
Does anyone have experience with such approaches and any recommendations?
Is it a terrible idea and should I just go back to inheritance (which I do not really want, since the rest of the project is written in the generic programming paradigm.)
If update function only uses internalState, you can simply store std::function<void(B&)> as a member, which is passed during construction:
class A
{
public:
template <typename F>
A(F&& func)
: updateFunc(std::forward<F>(func))
void doSomething()
{
updateFunc(internalState);
}
private:
using UpdateFunc = std::function<void(B&)>;
B internalState;
UpdateFunc updateFunc;
};
With this method, you can achieve nice flexibility while still maintaining single type instead of whole hierarchy.
Template-based solution may not be a good idea here - you only need to customize a single function, but making this a class template will cause to generate the whole class for every different function used as an argument. The only advantage is that you can specialize (or partially specialize) the logic, but it sounds like you doesn't need that.
Use inheritance or store update function as a member.
That will be a full academic answer :-)
First remark: What you want to do simply makes no sense!
Step by step:
You can use function pointers as template parameters as this:
using FUNCPTR_T = void(*)();
template < FUNCPTR_T f >
class A {
public:
void DoSomething()
{
(*f)();
}
};
void f1() { std::cout << "f1" << std::endl; }
void f2() { std::cout << "f2" << std::endl; }
int main()
{
A<f1> a1;
A<f2> a2;
a1.DoSomething();
a2.DoSomething();
}
But if you want to pass a parameter to your function, which is a class pointer ( this ), you need to define a function pointer which represents this like:
using FUNCPTR_T = void(*)(!!!POINTER_TO_THE_CLASS!!!);
But this class itself is a template which takes a pointer to a function which has a parameter which is a pointer to a class which takes a pointer to a function .... // endless recursion!
So your attempt simply fail at the point as you are unable to give a correct type for the template parameter.
And as already mentioned: Inheritance is much easier and works perfect. Using CRTP is often used to get access to the using class. Using std::function is much easier but moves the cost to runtime.
You can store a std::function and use lambdas: check out this simple class and its use as an example:
#include <functional>
#include <iostream>
#include <conio.h> // for _getch()
class A {
private:
int _state;
std::function<int()> _updater;
public:
A() : _state( 0 ) {}
void addUpdater( std::function<int()> updater ) {
_updater = updater;
}
void callUpdater() {
updateInternalState();
}
int returnState() const {
return _state;
}
private:
void updateInternalState() {
_state = _updater();
}
};
int main() {
A a;
a.addUpdater( []() { return 5; } );
a.callUpdater();
std::cout << a.returnState() << std::endl;
a.addUpdater( []() { return 10; } );
a.callUpdater();
std::cout << a.returnState() << std::endl;
_getch();
return 0;
}
Then to keep track of different instances of the same class, instead of inheritance you can use a map <id, this*> where id could be an int or a string. Makes for easy look up too. I think this might be better than templates in this situation because if you template this class where only the function differs it will generate a whole new class for each function change. Yes it does move things to runtime because of std::function, but it appears to be simpler to implement and manage.
I want a function return its real type, even it called in subclass. Here is the test code:
class Super
{
public:
Super(){};
virtual auto getSelf() -> decltype(*this)&
{
return *this;
}
void testSuper(){};
};
class Sub : public Super
{
public:
void testSub(){};
};
int main()
{
Sub().getSelf().testSuper();//OK
//Sub().getSelf().testSub();//Error
return 0;
}
In Objective-C, I can use instanttype to solve this.
But in C++, is it possible?
By the way, I do not want a template implementation, since it may increase the code size.
But in C++, is it possible?
Yes, and just like anything in C++, there is many ways to do it. But both ways require you to add something in the Sub class.
If you don't need virtual functions, then simply override (statically) that function:
struct Super {
auto getSelf() -> Super& {
return *this;
}
void testSuper(){};
};
struct Sub : Super {
auto getSelf() -> Sub& {
return *this;
}
void testSub(){};
};
int main() {
Sub().getSelf().testSuper(); //OK
Sub().getSelf().testSub(); //OK too!
return 0;
}
Of course, if you don't like copy pasting that code, you can always create a mixin class (a CRTP template):
template<typename Subclass>
struct AddGetSelf {
auto getSelf() -> Subclass& {
return static_cast<Subclass&>(*this);
}
};
You can the use that mixin in your classes like this:
struct Super : AddGetSelf<Super> {
using AddGetSelf<Super>::getSelf;
void testSuper(){};
};
struct Sub : Super, AddGetSelf<Sub> {
using AddGetSelf<Sub>::getSelf;
void testSub(){};
};
If you need virtual polymorphism, you can rely on covariant return types:
struct Super {
virtual auto getSelf() -> Super& {
return *this;
}
void testSuper(){};
};
struct Sub : Super {
auto getSelf() -> Sub& override {
return *this;
}
void testSub(){};
};
int main() {
Sub().getSelf().testSuper(); //OK
Sub().getSelf().testSub(); //OK too!
return 0;
}
Here's a live example at Coliru
If you are worried about binary size, consider static linking and link time optimisation.
I suggest you to try out both solutions and compare binary sizes, since template size increase can be cancelled out by compiler optimisation, and virtual polymorphism can prevent the compiler to do these optimisations.
I am going to go ahead with no. There is not convenient mechanisms in c++ to perform what you wish. (By convenient I mean avoiding any boilerplate, IMO options presented by Guillaume in his answer are certainly worth exploring.)
The code for different cases has to be duplicated. Types and objects cannot be created during run-time, like e.g. in C#. So you have to have code for each type.
You can do what you wish through static polymorphism, though those are templates. Maybe the compiler is smart enough to optimize each copy of getSelf, after all it's all returning the same pointer. But from the language point of view you have to provide a definition for each type.
There is run-time type information, but you would still need to if between the types effectively duplicating the code.
You might implement your example pure run-time using RTTI and dynamic cast, but it would be kinda ugly, as you would have to cast to reference manually... and dangerous.
E.g:
#include <iostream>
class Super
{
public:
Super(){};
virtual auto getSelf() -> decltype(*this)&
{
return *this;
}
void testSuper(){};
};
class Sub : public Super
{
public:
void testSub(){std::cout << "test\n"; };
};
int main()
{
Sub().getSelf().testSuper();//OK
dynamic_cast<Sub&>(Sub().getSelf()).testSub();//Danger
return 0;
}
But in C++, is it possible?
Short answer is - not directly as it happens in C#.
The type of this is the one of a pointer to the type of the subobject that offers the member function definition.
That is, Super * within getSelf definition in Super, Sub * within getSelf definition in Sub.
That said, note that the goal of double dispatching matches your requirements.
The drawback is that a call like Sub().getSelf().method(); is not possible anymore in this case.
It follows a minimal, working example:
struct Visitor;
struct Super
{
virtual void getSelf(Visitor &) = 0;
void testSuper(){}
};
struct Sub : Super
{
void getSelf(Visitor &) override;
void testSub(){}
};
struct Visitor
{
void accept(Sub &sub)
{
sub.testSuper();
sub.testSub();
}
};
void Sub::getSelf(Visitor &v)
{
v.accept(*this);
}
int main()
{
Visitor visitor;
Sub sub;
Super &super = sub;
super.getSelf(visitor);
}
What you want to be done as in Object-C is not possible in C++. They have different object calling models. See Object-C Messages. When you call object in C++ compiler must know everything about member function at compile time. In Object-C you don't call member function directly you send message to the object. So this is run-time binding.
I was just thinking about it and wondering if it's totally possible, just out of curiosity, as it would be very usefull I think. (but most of my ideas are crazy/insane anyway).
So here it goes:
Is it possible to create a class A, and class B, then add a member to class A by using class B?
Let's suppose we are making a game, or some program in which this would be usefull:
class Player
{
public:
float health;
};
Now, you think of a way to allow extensions by using include files or something:
#define INCLUDE_SPEEDO_METER
#ifdef INCLUDE_SPEEDO_METER
class PlayerSpeedo : public Player
{
public:
float absolute_speed;
//Do some Magic here & there
};
#endif
Now let's suppose we want to access the absolute speed of a player from the Player class like Player.absolute_speed.
Is this possible in any way?
No, that's not possible. You can't "inject" members into another class. Frankly, I can't see why you would ever want to. No one else than you would be aware of this "injected" member.
While you can't syntactically do what you are hoping to do, you can achieve something very close by storing a map in the base class.
class Player
{
public:
Player(float health = 0) { data["health"] = health; }
float health() const { return get("health"); }
float get(std::string const& field) const { return data[field]; }
protected:
std::map<std::string, float> data;
};
class PlayerSpeedo : public Player
{
public:
PlayerSpeedo(float absolute_speed) {data["absolute_speed" = absolute_speed; }
float absolute_speed() const { return get("absolute_speed"); }
};
What you're talking about is not possible in a statically typed language, but it would work in a dynamically typed language (like Python).
A way of achieving that in C++ would be to use a Map between string names of properties and some generic wrapper for property values.
Not quite what you're asking for, but would give you somewhat similar capabilities is the recent proposal for a future version of the C++ standard Call syntax: x.f(y) vs. f(x,y)
This would enable you to write a standalone function float absolute_speed(const Player& p) { return 0.0f; } that you could call via Player p; auto speed = p.absolute_speed() without changing the definition of Player. This is a similar idea to extension methods in C#.
Maybe you like the way which is often done to extend a base class by another class with a template like the following. There is no need for runtime polymorphism which is often a criteria for speed while optimizing can go down to the executed functions without stopping at the virtual functions.
As you can see from the example, it looks like injection of methods and attributes. C++11 offer it to use the constructor from the class which you use to extend the given class very simple. OK, this is a stupied example but maybe it give you an idea how the thing works.
#include <iostream>
class Empty
{
public:
void DoSomething() { std::cout << "Nothing" << std::endl;}
};
class Extender
{
private:
int x;
public:
Extender(int _x):x(_x) {}
void DoSomething() { std::cout << "Value " << x << std::endl; }
};
template <typename ExtendWith>
class User: public ExtendWith
{
public:
using ExtendWith::ExtendWith;
void DoIt() { ExtendWith::DoSomething(); }
};
int main()
{
User<Empty> userEmpty;
userEmpty.DoIt();
User<Extender> userExtended(100);
userExtended.DoIt();
}
I don't think the language could allow what you're trying to do without introducing inconsistencies.
I don't think you want to modify the actual type though, since what you describe is essentially converting a super-type instance into a sub-type instance. You could do this by adding a constructor to the sub-type...
class PlayerSpeedo : public Player {
public:
float absolute_speed;
explcit PlayerSpeedo(const Player& p, float absolute_speed=0, ...) : health(p.health) {
// copy Player values
}
Another option might be storing a reference to the original object, and decorating it. This doesn't alter the type though.
Is there some library that allows me to easily and conveniently create Object-Oriented callbacks in c++?
the language Eiffel for example has the concept of "agents" which more or less work like this:
class Foo{
public:
Bar* bar;
Foo(){
bar = new Bar();
bar->publisher.extend(agent say(?,"Hi from Foo!", ?));
bar->invokeCallback();
}
say(string strA, string strB, int number){
print(strA + " " + strB + " " + number.out);
}
}
class Bar{
public:
ActionSequence<string, int> publisher;
Bar(){}
invokeCallback(){
publisher.call("Hi from Bar!", 3);
}
}
output will be:
Hi from Bar! 3 Hi from Foo!
So - the agent allows to to capsule a memberfunction into an object, give it along some predefined calling parameters (Hi from Foo), specify the open parameters (?), and pass it to some other object which can then invoke it later.
Since c++ doesn't allow to create function pointers on non-static member functions, it seems not that trivial to implement something as easy to use in c++. i found some articles with google on object oriented callbacks in c++, however, actually i'm looking for some library or header files i simply can import which allow me to use some similarily elegant syntax.
Anyone has some tips for me?
Thanks!
The most OO way to use Callbacks in C++ is to call a function of an interface and then pass an implementation of that interface.
#include <iostream>
class Interface
{
public:
virtual void callback() = 0;
};
class Impl : public Interface
{
public:
virtual void callback() { std::cout << "Hi from Impl\n"; }
};
class User
{
public:
User(Interface& newCallback) : myCallback(newCallback) { }
void DoSomething() { myCallback.callback(); }
private:
Interface& myCallback;
};
int main()
{
Impl cb;
User user(cb);
user.DoSomething();
}
People typically use one of several patterns:
Inheritance. That is, you define an abstract class which contains the callback. Then you take a pointer/reference to it. That means that anyone can inherit and provide this callback.
class Foo {
virtual void MyCallback(...) = 0;
virtual ~Foo();
};
class Base {
std::auto_ptr<Foo> ptr;
void something(...) {
ptr->MyCallback(...);
}
Base& SetCallback(Foo* newfoo) { ptr = newfoo; return *this; }
Foo* GetCallback() { return ptr; }
};
Inheritance again. That is, your root class is abstract, and the user inherits from it and defines the callbacks, rather than having a concrete class and dedicated callback objects.
class Foo {
virtual void MyCallback(...) = 0;
...
};
class RealFoo : Foo {
virtual void MyCallback(...) { ... }
};
Even more inheritance- static. This way, you can use templates to change the behaviour of an object. It's similar to the second option but works at compile time instead of at run time, which can yield various benefits and downsides, depending on the context.
template<typename T> class Foo {
void MyCallback(...) {
T::MyCallback(...);
}
};
class RealFoo : Foo<RealFoo> {
void MyCallback(...) {
...
}
};
You can take and use member function pointers or regular function pointers
class Foo {
void (*callback)(...);
void something(...) { callback(...); }
Foo& SetCallback( void(*newcallback)(...) ) { callback = newcallback; return *this; }
void (*)(...) GetCallback() { return callback; }
};
There are function objects- they overload operator(). You will want to use or write a functional wrapper- currently provided in std::/boost:: function, but I'll also demonstrate a simple one here. It's similar to the first concept, but hides the implementation and accepts a vast array of other solutions. I personally normally use this as my callback method of choice.
class Foo {
virtual ... Call(...) = 0;
virtual ~Foo();
};
class Base {
std::auto_ptr<Foo> callback;
template<typename T> Base& SetCallback(T t) {
struct NewFoo : Foo {
T t;
NewFoo(T newt) : t(newt) {}
... Call(...) { return t(...); }
};
callback = new NewFoo<T>(t);
return this;
}
Foo* GetCallback() { return callback; }
void dosomething() { callback->Call(...); }
};
The right solution mainly depends on the context. If you need to expose a C-style API then function pointers is the only way to go (remember void* for user arguments). If you need to vary at runtime (for example, exposing code in a precompiled library) then static inheritance can't be used here.
Just a quick note: I hand whipped up that code, so it won't be perfect (like access modifiers for functions, etc) and may have a couple of bugs in. It's an example.
C++ allows function pointers on member objects.
See here for more details.
You can also use boost.signals or boost.signals2 (depanding if your program is multithreaded or not).
There are various libraries that let you do that. Check out boost::function.
Or try your own simple implementation:
template <typename ClassType, typename Result>
class Functor
{
typedef typename Result (ClassType::*FunctionType)();
ClassType* obj;
FunctionType fn;
public:
Functor(ClassType& object, FunctionType method): obj(&object), fn(method) {}
Result Invoke()
{
return (*obj.*fn)();
}
Result operator()()
{
return Invoke();
}
};
Usage:
class A
{
int value;
public:
A(int v): value(v) {}
int getValue() { return value; }
};
int main()
{
A a(2);
Functor<A, int> fn(a, &A::getValue);
cout << fn();
}
Joining the idea of functors - use std::tr1::function and boost::bind to build the arguments into it before registering it.
There are many possibilities in C++, the issue generally being one of syntax.
You can use pointer to functions when you don't require state, but the syntax is really horrid. This can be combined with boost::bind for an even more... interesting... syntax (*)
I correct your false assumption, it is indeed feasible to have pointer to a member function, the syntax is just so awkward you'll run away (*)
You can use Functor objects, basically a Functor is an object which overloads the () operator, for example void Functor::operator()(int a) const;, because it's an object it has state and may derive from a common interface
You can simply create your own hierarchy, with a nicer name for the callback function if you don't want to go the operator overloading road
Finally, you can take advantage of C++0x facilities: std::function + the lambda functions are truly awesome when it comes to expressiveness.
I would appreciate a review on lambda syntax ;)
Foo foo;
std::function<void(std::string const&,int)> func =
[&foo](std::string const& s, int i) {
return foo.say(s,"Hi from Foo",i);
};
func("Hi from Bar", 2);
func("Hi from FooBar", 3);
Of course, func is only viable while foo is viable (scope issue), you could copy foo using [=foo] to indicate pass by value instead of pass by reference.
(*) Mandatory Tutorial on Function Pointers