I have the following problem.
I got a class PluginLoader which oversees loading of plugins. It divides sub-stages of work to other classes like Plugin. Plugin calls functions of PluginLoader in its processing. Let's call that function AddData. Here, PluginLoader has to check if the data it receives is duplicate. For that, it uses a ConflictResolver class. Now, my problem is how to make an object of ConflictResolver available to PluginLoader. There are 3 ways I see out of this.
Use a ConflictResolverFactory class and create an object of ConflictResolver for PluginLoader.
Pass a constructed ConflictResolver* to the PluginLoader via its constructor or a member function SetConflictResolver and store it in a member variable and use it later. Both ways have drawbacks. If I pass it in the constructor, I will have to throw if the pointer is NULL. And I can't use exceptions as it is the custom here. If I pass it via SetConflictResolver, there is no way that I can guarantee that that function will be actually called by the user. Or I will have to check whether the member ConflictResolver* is NULL everywhere I use it.
Pass a ConflictResolver & to PluginLoaders Load method where all the work will be done. In turn, Plugins Load method has to accept a ConflictResolver & as well (though it has no use for it) and pass that back to AddData where PluginLoader will be able to use it.
Third method is safer compared to second. However, I have to pass around a reference even when it is not used.
If the first method cannot be used, what is the best way to do this?
Apologies for the wall :wq!
You could pass a ConflictResolver& to the PluginLoader constructor. You can now guarantee that the object is not null.
Related
I'm making a card game in C++ and I've made a a Button Class with an onClick() method. Every card is going to be a button, but I wan't each card to do something different when clicked. Is there a way to do this by somehow overriding the onClick() function for every instance, instead of creating 50 different class methods or 50 different classes?
I've tried creating a function for each different instance and passing it as a field in the class. Then, the onClick() function acts as a wrapper for each instance and calls the function passed as an argument in the Button constructor, but I'm trying to avoid adding a function argument in the Button constructor.
There are many possible solutions. One that popped up in my min is that you could have an array of 50 function pointers (or rather std::function objects) that each point to a function to handle the specific "card". Or just have a single such std::function object that you initialize to the correct function in the constructor initializer list (for example).
And if there's very little differing between the functions, perhaps it would be wiser to collect it into a single function anyway, and have e.g. a switch statement to do the little specific pieces that differs?
What you are asking for is commonly known as higher-order programming and function-objects
In c++, you may want to use eg. std::function(std-function) and store that on the card class - like you say. But since you don't want to pass it in the constructor (why ?) you could make the member optional eg. std::optional<std::function<void()> >
I extended the class wxFileSystemHandler to handle special protocols I use in my application. My implementation of wxFileSystemHandler::CanOpen() is called, recognizes the protocol and returns TRUE. But my implementation of wxFileSystemHandler::OpenFile() never gets called. I inspected the wxWidgets code and saw that the CanOpen() member function is called by the pointer that I registered. But when a call to OpenFile() is made they pass the pointer to a wxFileSystem::MakeLocal() member function that tries to get another pointer inside a hash map that, obviously, is not my instance.
Someone got a problem like this before?
Not sure what exactly are you doing, i.e. when do you expect your handler to be called, but in any case MakeLocal() is supposed to create a new instance of the same class if you mark the object as being dynamically creatable using wxRTTI macros and use the object as given otherwise. So if you really need the same object to be reused, you probably need to use wxDECLARE_ABSTRACT_CLASS() in its class. But OTOH why is it a problem to make a new instance?
I will describe the problem as simple as i can.
alright, here goes the problem;
Lets suppose we have a com component class with 3 of constructors where a constructor takes at least two of parameters. As we already know we instantiate the components via QueryInterface rather calling the classes' constructors therefore it seems it is not possible for a com client to set the constructor's parameters.
alright, here goes the question;
What is the best practical approach to allow a com client to instantiate a com component which requires at least two of parameters to be initialized?
Instead of directly returning object instances, your QueryInterface call can return factories. For example, instead of:
// implements IMyClass1 interface
return new MyClass1();
You would do:
// pointer to member that implements IMyClassFactory interface
return &m_myClassFactory;
// this could also be a static class instead of an object instance
The IMyClassFactory interface would have a create method that takes in the constructor arguments and returns the ultimate MyClass1 instance.
If its a pure COM component, the standard way of handling this is to implement Initialize(foo, bar) methods instead of separate constuctors and then call that immediately after COM instantiation. If the object has no sensible default state, then you can make it a member variable (pointer) in a COM object. From that COM object you will have your Initialize(foo, bar) functions. In each of these initialize function the correct version of your object will be instantiated. Every pass through function in your COM wrapper will need to check that your object is not NULL and return an appropriate HRESULT if it is.
One option would be to use a factory object; the creation functions would be all on the (stateless) factory object (on a different interface, of course), and pass back an initialized instance of the real object.
When I write COM servers, I don't usually allow my components to be instantiated by CoCreateInstance. Instead I export some bare functions (these can be described in IDL as well inside a module) from my DLL which accept the constructor parameters and return an interface pointer to the newly created object in an output parameter.
I like both Ates Goral's answer and Steve's and have upvoted both. Normally I would leave it at that, but I feel that this time I have to spell out my full take.
The "best", "right", "purest", "canonical" way to do this is undoubtely the factory pattern, as described by Ates. If you want to create a clean API, that's the road, hands down.
But... most of us are not busy creating public APIs for commercial products. For small internal projects with non-public APIs, I just want to get the job done. Having to implement an extra object just so I can expose a single factory method sounds rather overkill (particularly in C++). In most practical cases, I would just go for an Initialize(foo, bar) method as described by Steve. I would then make sure that every non-trivial method checks to see if the object has been initialized and returns a failure HRESULT if not.
So, I'm using the FMOD api and it really is a C api.
Not that that's bad or anything. Its just it doesn't interface well with C++ code.
For example, using
FMOD_Channel_SetCallback( channel, callbackFunc ) ;
It wants a C-style function for callbackFunc, but I want to pass it a member function of a class.
I ended up using the Win32 trick for this, making the member function static. It then works as a callback into FMOD.
Now I have to hack apart my code to make some of the members static, just to account for FMOD's C-ness.
I wonder if its possible in FMOD or if there's a work around to link up the callback to a specific C++ object's instance member function (not a static function). It would be much smoother.
You cannot directly pass a member function. A member function has the implicit parameter this and C functions don't.
You'll need to create a trampoline (not sure the signature of the callback, so just doing something random here).
extern "C" int fmod_callback( ... args ...)
{
return object->member();
}
One issue is where does that object pointer come from. Hopefully, fmod gives you a generic context value that will be provided to you when your callback is made (you can then pass in the object pointer).
If not, you'll just need to make it a global to access it.
I guess it supposed to work like this:
You can assign some user data to channel by calling FMOD_Channel_SetUserData. This user data should be a pointer to your C++ object that handles events.
Then you should write C-style callback that extracts that object by calling FMOD_Channel_GetUserData and then calls your C++ instance method on that object.
There is a non-portable, and pretty hackish solution that has the advantage of at least being thread-safe, which the "trampoline" methods are not.
You can generate the actual function machine code on the fly. The basic idea is that you have a template for your call-back function that takes an object pointer and a member-function pointer and gives you a block of heap memory that you can pass to the library as a C call-back function, that will, when called, turn around and call the member function on that object.
It's messy, and you'll have to provide an implementation for any new platform (any time the calling convention changes), but it works, is thread-safe. (Of course you'll also have to watch out for DEP). The other thread-safe solution is to resort to thread-local storage (assuming that you know the call-back will happen on the same thread as the call you made).
See http://www.codeproject.com/KB/cpp/GenericThunks.aspx for an example of how you could go about generating thunks.
Using only a function pointer (and no additional separate object pointer) for a C callback is a broken design, in my humble opinion.
If the function were, instead, FMOD_Channel_SetCallback(channel, callbackFunc, callbackObj), then your static method just takes an instance of the object, then calls callbackObj->func() (which obviously can be non-static).
you need to use a trampoline and store the pointer to the object you want to get the member function called on in a global or static variable, i.e.
Object *x;
void callback_trampoline() { x->foobar(); }
...
FMOD_Channel_SetCallback(CHANNEL, callback_trampoline);
I have a class which defines a historical extraction on a database:
class ExtractionConfiguration
{
string ExtractionName;
time ExtractionStartTime;
time ExtractionEndTime;
// Should these functions be static/non-static?
// The load/save path is a function of ExtractionName
void SaveConfigruation();
void LoadConfiguration();
}
These ExtractionConfigurations need to be saved to/loaded from disk. What is the best way of organising the save/load functions in terms of static/non-static? To me, it is clear that SaveConfiguration() should be a member function. However with LoadConfiguration(), does it make more sense to call
ExtractionConfiguration newExtraction;
newExtraction.LoadConfiguration();
and have a temporary empty instance or make the load function static
static ExtractionConfiguration LoadConfiguration(string filename);
and just call
ExtractionConfiguration newExtraction = ExtractionConfiguration::LoadConfiguration(filename);
which feels neater to me, but breaks the 'symmetry' of the load/save mechanism (is this even a meaningful/worthwhile consideration?).
I suppose asking for the 'best' answer is somewhat naive. I am really trying to get a better understanding of the issues involved here.
P.S. This is my first question on SO, so if I have not presented it correctly, please let me know and I will try and make the problem clearer.
You should consider using Boost.Serialization style serialization function that avoids having separate functions for saving and loading (even if you don't use the library itself).
In this approach you can pass the function any type of object that has operator&, to perform an operation on all the member variables. One such object might save the data to a file, another might load from a file, third might print the data on console (for debugging, etc).
If you wish to keep separate functions, having them as non-static members might be a better option. For the saving function this is obvious, but loading is a different matter because there you need to construct the object. However, quite commonly loading is done by default-constructing and then calling the load non-static member function, for symmetry reasons, I guess.
Having the loading as a function that returns a new object seems better in some ways, but then you need to decide how it returns the object. Is it allocated by new, or simply returned by value? Returning by value requires the object to be copyable and returning a pointer mandates the resource management scheme (cannot just store the object on stack).