I'm creating event system. It's based under boost::signals. To make the work easier I'm using typedef for the function signatures.
Everything is okey until I need creating of some new event trought event's system method. I have to create the typedef dynamically on given type to the template function. The problem is the name of typedef.
Some pseudocode I would have:
template<typename EventType>
void create(const string &signalName)
{
typedef EventType signalName;
// ...
}
Is it possible to make such typedef (their names) with some passed string or data or something else? I don't want to make user care about of this.
UPD: So, I have some typedefs list of function signatures - events. I have some templated function for connecting slots, for example. I don't want to force user to input signature by his hands again every time (user is programmer which will use the event system). So I just use my typedefs from special namespace into template argument.
typedefs only matter during compilation. As far as I know it's just an alias for a type.
Template parameters are, by definition, compile time entities. You can not dynamically create template classes on the fly during program execution as far as I am aware.
In this case, I wouldn't go for typedef's. If you want to have several types of events and create them dynamically, you can use a simple class containing the information about the event type. When you have an event, you link it to the event type created before.
Something like this:
class EventType
{
private:
string type;
EventType(string type);
};
class Event
{
private:
string event_name;
EventType *event_type;
Event(string event_name, EventType event_type);
};
...
void create(const string &signalName)
{
EventType *event_type = new EventType("type_x");
Event *event = new Event("event_x", event_type);
}
Related
Class World is designed to spawn Actors.
Actors can be different types: it's can be Cat, can be Dog, can be Tree, everything, the only similar thing is that they all derived from Actor.
And there is also command line, it gives World a string where written next things:
what_to_do string_leftover. There if what_to_do equals "Spawn" then first word of string_leftover must be type name, second - Actor name.
The problem is that number of Actors can be indefinite - I don't really sure about their count and I'am really scared of forget to write their Spawn overload manually.
If very simple:
I entered in console: "SelectWorld World1" then "Spawn PhysicalPendulum OneMorePendulum". This will select world named World1 (this is working perfectly) and spawn Actor of type PhysicalPendulum with name OneMorePendulum.
Problem: I can't elegantly determine what type I should spawn from string.
Why:
All solutions I know requires to create "string to type determiners" not in actor-derived class header/object file.
I mean I can use switch (pointer-to-function map), but each time I create new Actor type I need to return to that Spawn function and write down new type to spawnables, there is a slight chance that I can totally forget about it and looooooong time of debugging will be awaiting me.
I can create static class instance with macro, but there is no guarantee that Spawner will be created before this instance initializes.
I thought about tricks with macros, but they can't be extended, like if certain define had "definition_body" I can't add "another_definition_body" to it and get "definition_body another_definition_body".
How can I elegantly spawn type from string?
Declare a global function/macros that will 'register' newly create class to the list of known e.g.
//SpawnActor.h
#pragma once
using std::string;
using std::map;
using std::function;
class Actor;
class ActorSpawner
{
public:
typedef function<Actor()> SpawnFunction;
static void RegisterActorClass(const string& name, const SpawnFunction& function)
{
s_spawnClasses[name] = function;
}
void SpawnClass(const string& name)
{
// You'll need to validate name
Actor* a = s_spawnClasses[name]();
//...
}
private:
static map<string, function<Actor()> s_spawnClasses
};
//SpawnActor.cpp
#include "SpawnActor.h"
map<string, function<Actor()> SpawnFunction::s_spawnClasses();
//TreeActor.h
class TreeActor : public Actor
{
...
};
//TreeActor.cpp
#include "TreeActor.h"
ActorSpawner::RegisterActorClass("TreeActor", [](){return new TreeActor();})
For your code to create an object, you must know the type of the object you are creating. At some point you must say thing* = new Thing()
You can have a factory that knows all the types of objects allowed to be created. If you use a standardised naming convention you can use token pasting. thing* = new Thing ## string_name. i.e. string = "Robot". #define ABC(name) return new Thing ## name. class ThingRobot {}; etc...
I'm programming a plugin API interface for an application. The plugins are loaded as shared libraries at run time. They have access to the application API through an interface, such as the following:
class IPluginAPI
{
public:
virtual bool IsPluginsLoaded(void) = 0;
virtual bool IsHookingEnabled(void) = 0;
// And about 50 more methods
};
Plugins can request to 'listen' on certain events (such as MouseClick, MouseScroll etc.). These functions make up a total of >300 different events. Normally I would have done something like this:
extern "C" void SetEventHooks(APITable& table)
{
table.MouseClick = &PluginMouseClickEvent;
table.MouseMove = &PluginMouseMoveEvent;
}
Whereas the SetEventHooksfunction resides within the plugin library and is called from the application, and the plugins can listen to functions of interest by pointing to their functions. This is not the method I want to use, but I want to offer some kind of abstraction instead. This is what I had in mind:
// Interface IPluginAPI supplies a 'SetEventHook` method such as
void SetEventHook(HookID id, void * callback);
In this case HookID is a strong typed enum which contains all function IDs:
enum class HookID
{
MouseClick,
MouseMove,
// ...
};
So the plugin would use this function to listen to events:
pluginAPI->SetEventHook(ID::MouseClick, &myCallback);
The problem with this approach is that it is not type-safe and I cannot use templates directly (since this is done at runtime as libraries). I don't want to expose 300 different functions either for each event (e.gSetHookMouseMove(void (*)(int, int)) and so on). My last idea, is that the plugins have a utility template function which makes this type safe, but I'm not sure how to implement this in a simple way (and without boilerplate code):
template <typename T>
SetEventHook(HookID id, T callback)
{
if(typeof(T) == decltype(/* function type of the ID */))
gPluginAPI->SetEventHook(id, callback);
else static_assert("INVALID FUNCTION TYPE");
}
So to put it simple; how can I enable my plugins to hook to certain events in a dynamic type-safe way without exposing a complete function table and/or >300 methods for each event?
NOTE: I used function pointers for simplification, but I want to use std::function
As suggested by Kerrek, you can use traits policy to solve your problem. Basically as a part of public API you have to include structures defining callback type for each of your hook id.
// The default traits. If you don't want to have default traits comment body
// of this type out (including curly braces).
template <HookID id>
struct CallbackTraits
{
typedef void (*CallbackType)();
};
// Traits for MouseClick
template <>
struct CallbackTraits<HookID::MouseClick>
{
typedef void (*CallbackType)(int);
};
// Traits for MouseDoubleClick are the same
template <>
struct CallbackTraits<HookID::MouseDoubleClick> : CallbackTraits<HookID::MouseClick> {};
// Traits for MouseMove
template <>
struct CallbackTraits<HookID::MouseMove>
{
typedef void (*CallbackType)(int, int);
};
// actual hooking function
template <HookID id>
void SetEventHook(typename CallbackTraits<id>::CallbackType callback)
{
// do something with id and the callback
}
Now you can use this API following way:
// handlers prototypes
void MouseClicked(int button);
void MouseMoved(int x, int y);
void SomeEvent();
int main()
{
// compiles ok
SetEventHook<HookID::MouseClick>(MouseClicked);
SetEventHook<HookID::MouseMove>(MouseMoved);
// won't compile - function signature incompatible
SetEventHook<HookID::MouseDoubleClick>(MouseMoved);
// will compile if you left default traits body uncommented
SetEventHook<HookID::HookWithNoTraitsDefined>(SomeEvent);
return 0;
}
I've uploaded a working sample here.
I'm working on a game project that features scratch-built controls rendered into an opengl context; things like buttons, scrollbars, listboxes, etc. Many of these controls are nested; for example, my listbox has a scrollbar, a scrollbar has 3 buttons, etc.
When a scrollbar changes value, I'd like it to call 'some' function (typically in it's parent object) that responds to the change. For example, if the listbox has a slider, it should instantiate the slider, then tell the new slider that it should call the listboxes 'onScroll(float)' function. All of the controls share a common base class, so I could have a 'base* parent' parent pointer, then do 'parent->onScroll(val)'. The problem though is what happens when the parent doesn't inheirit from base; there'd be no virtual onScroll() to follow through, so the top-level parent would have to periodically check to see if any of the child controls had changed value. This would also clutter up other controls, since they may not even have children, or may require different event types like when a list entry object is selected, etc.
A better solution would be to have the child object maintain a generic function pointer (like a callback), which can be set by the parent, and called by the child as necessary. Something like this:
typedef (*ptFuncF)(float);
class glBase {
public:
//position,isVisible,virtual mouseDown(x,y),etc
};
class glDerivedChild : public glBase {
public:
glDerivedChild();
~glDerivedChild();
void changeValue(float fIn) {
Value = fIn; //ignore these forward declaration errors
(*callBack)(fIn);
}
void setCallBack(ptFuncF pIn) {callBack = pIn;}
ptFuncF callBack;
float Value;
};
class glDerivedParent : public glBase {
public:
glDerivedParent() {
child = new glDerivedChild();
child->setCallBack(&onScroll);
}
~glDerivedParent() {delete child;}
void onScroll(float fIn) {
//do something
}
glDerivedChild* child;
};
class someFoo {
public:
someFoo() {
child->setCallBack(&setValue);
}
void setValue(float fIn) {
//do something else
}
glDerivedChild child;
};
I'm kinda new to function pointers, so I know I'm (obviously) doing many things wrong. I suspect it might involve something like "typedef (glBase::*ptFuncF)(float);" with the 'onScroll(f)' being an overridden virtual function, perhaps with a generic name like 'virtual void childCallBack(float)'. I'd prefer to keep the solution as close to vanilla as possible, so I want to avoid external libraries like boost. I've been scratching my head over this one for the better part of 8 hours, and I'm hoping someone can help. Thanks!
I think, what you want is some kind of events or signals mechanism.
You can study, how event processing is organized on Windows, for example. In short, your scrollbar generates new event in the system and then system propagates it to all elements, registered in the system.
More convenient mechanism is signal/slot mechanism. Boost or Qt provides such tools. I'll recomend this solution.
But if you still want to use just callbacks, I'll recommend using std::function (boost::function) (combined with std::bind (boost::bind), when required) instead of raw function pointers.
Use boost::function (or std::function if available). Like this (using your notation):
typedef std::function<void (float)> ptFuncF;
//...
void setCallBack(const ptFuncF &pIn);
//...
child->setCallBack(std::bind(&glDerivedParent::onScroll, this, _1));
//...
child->setCallBack(std::bind(&someFoo::setValue, this, _1));
A function pointer to a member function of a class has such a type:
<return type> (<class name>::*)(<arguments>)
For example:
typedef void (glBase::*ptFuncF)(float);
^^^^
by the way, you have forgot the `void` in your `typedef`
ptFuncF func = &glDerivedChild::onScroll;
And you use it like this:
glDerivedChild c;
(c.*func)(1.2);
In your particular example, the function is a member of the derived class itself, therefore you should call it like this:
(c.*c.callback)(1.2);
the inner c.callback is the function pointer. The rest is exactly as above, which is:
(class_instance.*function_pointer)(arguments);
You might want to take a look at this question also.
Ok, the workaround I came up with has some extra overhead and branching, but is otherwise reasonable.
Basically, each callback function is implemented as a virtual member function that recieves the needed parameters including a void* pointer to the object that made the call. Each derived object also has a base-class pointer that refers to the object that should recieve any events that it emits (typically its parent, but could be any object that inheirits from the base class). In case the control has multiple children, the callback function uses the void* pointer to distinguish between them. Here's an example:
class glBase {
public:
virtual onChildCallback(float fIn, void* caller);
glBase* parent;
};
class glSlider : public glBase {
public:
glSlider(glBase* parentIn);
void changeValue(float fIn) {
Value = fIn;
parent->onChildCallback(fIn, this);
}
float Value;
};
class glButton : public glBase {
public:
glButton(glBase* parentIn);
void onClick() {
parent->onChildCallback(0, this);
}
};
class glParent : public glBase {
public:
glParent(glBase* parentIn) : parent(parentIn) {
childA = new glSlider(this);
childB = new glButton(this);
}
void onChildCallback(float fIn, void* caller) {
if (caller == childA) {
//slider specific actions
} else if (caller == childB) {
//button specific actions
} else {
//generic actions
}
}
glSlider* childA;
glButton* childB;
};
Besides a reasonably small amount of overhead, the scheme is flexible enough that derived classes can ignore certain components or omit them altogether. I may go back to the function pointer idea later (thanks shahbaz), but half the infrastructure is the same for both schemes anyway and the extra overhead is minimal, especially since the number and variety of controls will be rather small. Having the callback function use a nested response is actually a little better since you don't need a separate function for each child object (eg onUpButton, onDownButton, etc).
Class member functions in Python have to explicitly declare a self parameter which represents the class instance. Is there a way to get a hold of self from C++, by using Boost?
class FooBar
{
public:
void func() {
}
};
// A wrapper for the above class
struct FooBar_W
: public FooBar
{
void func(boost::python::object self) {
// Do smth with `self`
FooBar::func();
}
};
BOOST_PYTHON_WRAPPER(module)
{
class_<FooBar_W>("FooBar")
.def("func", &FooBar_W::func)
;
}
Edit: Why I want self
I'm writing an event system for my game and I want the scripter to be able to define new types of events. I need a way to distinguish between different types of events. My Python code looks something like this:
class KeyboardEvent(Event):
pass
def onKeyPress(event):
pass
# EventManager is defined in C++
em = EventManager()
# This is how I register a new callback function with the manager
# The `onKeyPress` function will now only be notified when an event
# of type `KeyboardEvent` occurs. (Notice that I passed the actual
# class object, and not an instance of it.)
em.addEventHandler(KeyboardEvent, onKeyPress)
# This is how I queue new events
# (This time I pass an instance of an event, not a type of event.)
em.queueEvent(KeyboardEvent())
The manager needs to figure out what type of event I just queued. I figured I should do something like type(event).__name__ (but in C++, not in Python). This way I can determine the type and know which functions to notify of the event. I want to get self in C++ so I can access the __name__ attribute of its type.
I could have the scripter manually edit a new field that holds the name of the type, but why? That information already exists (the __name__ attribute) so why duplicate it, but more importantly, why bother the scripter with implementation details?
It's doable. The way to do it can be found in the link below; that page documents one way (the old way) to expose pure virtual functions. The example can be adapted to other needs, though.
> http://wiki.python.org/moin/boost.python/OverridableVirtualFunctions#Pure_Virtual_Functions
it's an old question, but for those who are still looking for a reasonably simple solution:
Static function (non-member as well as member) receive a const boost::python::object& self as the first argument. So you can do the following:
class FooBar
{
public:
static void func(const boost::python::object self) {
FooBar& thisref = boost::python::extract<FooBar&>(self)();
// use self as well as thisref
}
};
};
BOOST_PYTHON_WRAPPER(module)
{
class_<FooBar>("FooBar")
.def("func", &FooBar::func)
;
}
self in python is this in C++.
You can think of the line FooBar::func(); as translating to static_cast<FooBar*>(this)->func()
Is there any efficient way in C++ of generating an ID unique to the class, not to the instance? I'm looking for something of this level of simplicity (this generates an ID for every instance, not for every class type):
MyClass::MyClass()
{
static unsigned int i = 0;
id_ = i++;
}
Edit: Why I want unique IDs.
I'm writing a game. All entities in my game will have different states they can be in (walking left, jumping, standing, etc); these states are defined in classes. Each state needs to have its own ID so I can identify it.
You can try this, but it's not-deterministic.
int id_count = 0;
template <typename T>
int get_id()
{
static int id = id_count++;
return id;
}
Then just use:
get_id<int>(); // etc.
Of course, this isn't thread safe.
Again, it's not deterministic: the IDs are generated the first time you call the function for each type. So, if on one run you call get_id<int>() before get_id<float>() then on another run you call them the other way round then they'll have different IDs. However, they will always be unique for each type in a single run.
Basically you are asking for a custom rolled RTTI solution, that you can selectively apply to classes.
This can start from very crude preprocessor stuff like :
#define DECLARE_RTTI_CLASS(a) class a { \
inline const char * class_id() { return #a };
.. to a more sophisticated solutions that track inheritance etc, essentially partially duplicating compiler RTTI functionality. For an example, see Game Programming Gems #2, Dynamic Type Information
Previous discussions on gamedev on the same subject are also worth reading
Use your MyClass as a primitive, and incorporate a static instance of one into each class you want to ID.
class MyOtherClass1 {
static MyClass id;
};
class MyOtherClass2 {
static MyClass id;
};
[etc.]