tags:

views:

73

answers:

2

Hi,

I have a program in C++ with plugins (dynamic libs). In the main program, I want to execute a static function to check if i can create a object of this type.

An example without dynamic libs (aren't neccesary to understand the problem):

#include "libs/parent.h"
#include "libs/one.h"
#include "libs/two.h"

int main(int argc, char * argv[])
{
    Parent* obj;

    if (One::match(argv[1]))
        obj = new One();
    else if (Two::match(argv[1]))
        obj = new Two();
}

Now, i have a interface class named Parent. All plugins inherit from this class. Ideally, I have a virtual static function in Parent named match, and all the plugins need to reimplement this function.

The problem with this code is that i can't do a static virtual function in C++, so i don't know how to solve the problem.

Sorry for mi english, i did my best

+3  A: 

What you have here is classic factory pattern. You want to create an interface named IPluginFactory which would have two methods - match and create (or, optionally, combine them both in a single method). Then each of your plugin DLLs would have a class that implements this interface.

    Parent obj;
    IPluginFactory *one = new OneFactory();
    IPluginFactory *two = new TwoFactory();

    if (one->match(argv[1]))
        obj = one->createObj();
    else if (two->match(argv[1]))
        obj = two->createObj();
Fyodor Soikin
This answer doesn't address `virtual static` functions.
Xavier Ho
It does address the question, though.
Fyodor Soikin
I don't see how this relates to static functions. Can you enlighten me?
Xavier Ho
It solves the problem the poster has. It does not relate to static methods.
Fyodor Soikin
Fair enough. I see now. `=]`
Xavier Ho
Perfect!. This solves my problem. Thank you
You're welcome :-)
Fyodor Soikin
A: 

You could add some static string to each of your plugins, that would hold it's name. Or make some struct called PluginID and add this string to this struct (and probably something else plugin-specific).

Now matching in runtime seems to become very simple. Just check whether that static identification string from your plugin matches your argv.

This is a commonly used implementation of a so-called "your-own-and-simple-rtti", guess it would solve your problems.

Kotti
The `match` methods do not necessarily check for simple equality.
Fyodor Soikin
I do agree that creating an object factory would be a better solution, but my intuition actually says that this simple rtti-implementation is what would work in this particular case
Kotti
The problem is that the match() method is more complicated than simple comparation of the string passed by argv, but thank you!