void Pointer casting

so not sure how to do this but if I have…

  
void* content;  
  
void pass(ofImage* typ) {  
     static_cast <ofImage*> (content);  
     content = img;  
}  
void pass(ofxCvGrayscaleImage* typ) {  
     static_cast <ofxCvGrayscaleImage*> (content);  
     content = typ;  
}  
  
void draw() {  
   content->draw();  
}  

I have a void pointer and i want to cast it according to the type i pass in through the pass() function. i have no idea if this is how you do this. It doesnt work but anyone have a suggestion.

Hey todd

the type of the variable is always the same, so you are not transforming the initial declaration by doing:

  
static_cast <ofImage*> (content);   

content is still a void*

What you can do is:

  
(static_cast <ofImage*> (content))->draw();  

there you’re saying, treat this void * as an ofImage because i know i previously instantiated like that type.

so if you have some fixed number of types you want to deal with, you can for example do something like:

  
  
#define TYPE_OF_IMAGE 0  
#define TYPE_OFX_GRAYSCALE_IMAGE 1  
  
void* content;  
int content_type;  
  
void pass(ofImage* typ) {  
     content_type=TYPE_OF_IMAGE;  
     content = img;  
}  
void pass(ofxCvGrayscaleImage* typ) {  
     content_type=TYPE_OFX_GRAYSCALE_IMAGE  
     content = typ;  
}  
  
void draw() {  
switch(content_type){  
   case TYPE_OF_IMAGE:  
         ((ofImage*)content)->draw();  
   break;  
   case TYPE_OFX_GRAYSCALE_IMAGE:  
         ((ofxCvGrayscaleImage *)content)->draw();  
   break;  
}  
}  

The cleanest way to do this is if all drawable objects inherit from a common DrawableObject abstract base class.

  
  
class ofDrawableObject {  
public:  
    virtual void draw() = 0;  // pure virtual. doesn't actually do anything but provides a Java style interface definition for subclasses  
}  
  

and then define any classes which are visible as extensions of this

  
  
ofImage : public ofDrawableObject {  
...  
}  
  
ofxCvGrayscaleImage : public ofDrawableObject {  
...  
}  
  
ofxSlider : public ofDrawableObject {  
...  
}  
  

then you don’t need to use void pointers or any casting, but can just use ofDrawableObject pointers

  
  
ofDrawableObject* content;  
  
void pass(ofDrawableObject* c) {  
     content = c; // can pass any object which is a subclass of ofDrawableObject*  
}  
  
void draw() {  
   content->draw(); // will automatically use the correct draw method depending on the class  
}  
  

Any such mods in the core would be invisible to the normal user, fully backwards compatible… but if you do want to get deeper into OOP the possibility is there. Until then, Arturo’s method is the only way…

or templates :slight_smile:

but that’s a really good idea, some base classes like ofDrawable, ofVideo or something like that can be very transparent to the user and really useful for this cases

I think templates is what you want to go with here. I find a lot of people here are a bit afraid(maybe afraid is not the appropriate word here) of templates because of how abstract they can be to understand but I think they are a great tool.

This is an interesting thread. I was thinking about how to do this recently and the only way I could think of was via some form of pointer indirection like polymorphism (aka virtual functions), which memo covered quite well.

My other thought was function pointers, but this doesn’t work if you have an object and you’re trying to keep type safety because each function will have the object as its first argument, so each function pointer will be of a different type:

  
  
void (*fptr1)(ofImage *);  
void (*fptr2)(ofxCvGrayscaleImage *);  
etc.  
  

AFAICT, templates suffer from the same issue. I’m not seeing how they help in this case. Certainly they reduce the amount of code you have to write as you can simply do:

  
  
template<class Img>  
void pass(Img *img) {/*definition here*/}  
  

but the goal here is to use them with a generic object, which a template does not make. Templates allow for generic descriptions of objects and functions that when instantiated become class/type specific. For instance:

  
template<typename T>  
class A{};  
  
A<int> *a;  
A<float> *b;  
  
  

You can’t assign a to b or vice-versa because they are totally different objects. They don’t share an inheritance tree. They’re more like parallel lineages. If it was:

  
template<typename T>  
class B : public A  
{}  
  
A *a;  
B<int> *b;  
B<float> *c;  
a = b;  
a = c;  

would be valid because of the shared superclass, which if you wanted to use any of the functions in class B from a pointer of type class A, you would need polymorphic behavior via virtuals.

As a side not, you need to be very careful when dealing with casts from a void* to another type when you have multiple inheritance. It’s possible for a pointer to an object that inherits from >1 other class to be slightly offset from the start of the memory block, which can cause crashes. If you don’t have multiple inheritance, then it’s nothing to worry about in terms of crashing but perhaps code could be reorganized better.

That said, C++ is not a dynamic language and sometimes you have to carry type information as an int or enum along with a void* cast just to inject some dynamicity into the system. For a wide-spread example of such design, see any scripting language and how it handles C++/C objects. Also anything dealing with callbacks will more often then not use void* as well although there are alternatives such as using functors or signals/slots but these have their own tradeoffs in trying to shim dynamicity into C++.

wow what great feed back. I like aturos approach it works best for what I’m doing. Really good stuff in this thread

I’ve been also using poco delegates lately, for something like this, but they’re not as flexible as i thought at first and the sintax is fairly complicated

EDIT: yes, they were :slight_smile:

What’s not exactly clear to me at this point is how the original code posted fits into the context of the larger application. The two solutions mentioned so far in this thread are the two possible forms of polymorphism in C++: dynamic polymorphism (virtuals) and static polymorphism (templates).

On a quick tour through google using the following search - dynamic c++ polymorphism templates - I came across quite a range of discussions about this issue but no definitive implementation of using templates for dynamic polymorphism. I’d be interested to see if anyone has come across such an example. Basically it boils down to being able to capture type information dynamically and cache any pertinent information such that it can be used to call through to the proper function when needed.

To get back to the original thread post though, I would say it really depends on your situation. It might be entirely possible to employ a basic form of static polymorphism in your situation, in which case that would certainly be your best bet since it’s objectively faster in all cases due to the lack of vtable indirection. Plus, it’s actually simpler to code up because you don’t have to rearchitect the inheritance tree.

In any case, please let us know the design you settle on and the reasoning behind it as I think it will help others navigate this subtle area of C++ in the future.

ok, so I’ve just find how to do that with delegates. I’ve been trying to use it since Memo asked me something similar at the ofLab.

I’d managed to make it work for different functions with the same signature but not for different classes. but that’s not more useful tha function pointers, but looking at the events code in poco, there’s an AbstractDelegate class, and there’s the key. I’m not using the original problem posted by todd, because don’t know if void arguments are supported, but the idea is something like:

  
Poco::AbstractDelegate<string> * delegate;  
  
void pass(AbstractDelegate<string> * delegate) {  
     this->delegate=delegate;  
}  
  
void draw() {  
   delegate->notify(this,"some string");  
}  

So to call it you should do something like:

  
object->pass(new Poco::Delegate<ofxStringRenderer1,string>(stringRenderer1,&ofxStringRenderer::drawString));  

so with this you can pass any method of any class as a parameter through the delegate.

It’s a mixture between the two kinds of polymorphism but instead of using inheritance for the called class you use it in the delegate, that is basically a class that contains a pointer to a function. By using templates to indicate the class that contains that method you manage to be able to call any kind of method inside any class.

Indeed it’s not usefu,l as is, for what todd wants to do because the called object method should have this signature:

  
void ofxStringRenderer::drawString(void * sender, string &string_to_render);  
  

but the same idea can be applied to create a delegate for diferent signature methods.

I could be wrong, but I think the void* thing was an attempt to get around the lack of polymorphic types so I don’t think the delegate code is necessarily inapplicable to the original situation. However, it does seem to be a bit of a bear syntax-wise and I’d be especially curious to know how much it bloats the compiled binary and symbol table.

I’ve tried using Loki::Functors (Loki is a library implementing a good chunk of Scott Meyer’s C++ metaprogramming techniques http://loki-lib.sourceforge.net/) and it seriously bloated my compiled code. Similarly to delegates, it allows for arbitrarily calling of functions with arbitrary arguments.

Also up for consideration is the amount of indirection that the delegate process creates. Is it going to be any faster than using virtuals? Certainly delegates have their use when you don’t have access to the inheritance hierarchy. It’s a very common design pattern in Cocoa for instance. Still, I’m wondering if there’s a simpler way to use templates for this purpose.

yes the syntax is fairly complicated, but for some cases is really powerful. As of the indirection problems: the code for the delegates is inlined so it should be just the same as if you just call the function

I was curious, so I took a look at Poco delegates. Essentially I was trying to see how they get around the type dispatching issue at runtime and, well, they use virtuals. AbstractDelegate::notify is a virtual function. If it wasn’t, firstly the name Abstract would be misleading in a C++ context and second, there would be no way for it to handle arbitrary function calls. Parts of it may be inlined, but the delegate->notify call certainly isn’t.

This is where static polymorphism meets dynamic polymorphism. There’s simply no typesafe (in a compile-time sense) way to work this in C++ without going through the incredible circumlocutions that Loki::Functor does, which in my experience is not a good trade-off.

If I’m wrong, I’d love to see some code that disproves what I’ve said, but I’ve tried to code up a simple example and I can’t quite get there.

Essentially I was trying to see how they get around the type dispatching issue at runtime and, well, they use virtuals. AbstractDelegate::notify is a virtual function.

yes, that’s what i meant with a mixture of the two kins of polymorphism, it uses templates to indicate the class that contains the method, and virtuals to be able to call any of that classes. And yes, there’s a level of indirection, but just the same as if you use inheritance for the called class and you get a really powerful artifact with which you can call any function in any class.

About the typesafety I don’t understand very well what you mean, can you put an example?

Right! By typesafety, I meant the compiler checks what types you’re using and if they’re compatible. This is what the delegate mechanism is doing. I haven’t used it, but if you used a method on an object that didn’t belong to its class, it should check this during compilation and give an error. If it doesn’t, then a good portion of what the templates delegates are useful for is missing. The other option is to eradicate types from the compiler’s perspective and cast to void*. It’s perfectly possible to have a void*-based dispatching mechanism provided some extra data such as an int or enum indicating class type. The issue with this method is that the compiler can’t check it and thus it can’t optimize it.

Well, indeed there’s type checking at compile time with this kind of delegates.

Both the type of the called class and the type of the parameter of the function are determined by the template in the instantiation of the delegate:

  
object->pass(new Poco::Delegate<ofxStringRenderer1,string>(stringRenderer1,&ofxStringRenderer::drawString));  

in:

  
  
new Poco::Delegate<ofxStringRenderer1,string>  

so in the constructor you cannot pass a wrong instance or a function that doesn’t belong to that class without the compiler noticing it:

  
(stringRenderer1,&ofxStringRenderer::drawString);  

Hi… sorry to resurrect a dead thread, but this is the closest example to addressing my current problem that I’ve been able to find. Fascinating thread…

I’m dealing with an issue that I think some of these solutions - particularly Memo’s - might serve, but am trying to discern that a little more closely first.

I have an abstract base class GUI which has a number of methods and properties that are inherited down into classes that represent different media types - ie. IMAGE / VIDEO / SOUND etc.

Currently each subclass has a vector to hold the number of created objects of it’s type, and the GUI class has it’s own vector that is given a push back whenever any of the subclassed objects are instantiated, so I have a master vector of all the objects (and can just loop through those instead of looping through one subclass’s vector against itself and against all the vectors of all the other subclasses…). From what I understand, this strategy could be mitigated by the Boost library, but… well, you know.

The problem that I am running into is that as I loop through my master vector, a method call calls the superclass method, where I want to call the overridden subclass method. Eg:

  
  
for (int i = 0; i < allObjects.size(); i++) {  
  allObjects[i]->draw();  // this calls the superclass method  
}  
  

Now obviously the size of the master vector is going to be larger than the subclass vectors, so I can’t match i to i in this case…
I can imagine passing another parametre in the instantiation and then doing some type of two-dimensional vector/array/lookup table, but it seems to me that this would result in a lot of computational overhead, and a pointer would be more efficient.

The ideas cast about in this thread seem like they are addressing this type of problem - again, particularly Memo’s, or so I imagine, as the architecture of my program seems to match his example…

I’d be curious to see any responses as to the match/mismatch, or anyone else that has encountered this type of issue before…

Thanks in advance,

~ J

BUMP