Re: c++ and IoC
On 3 ao=FBt, 10:33, Vladimir Jovic <vladasp...@gmail.com> wrote:
Hello,
Following this :http://www.codinginlondon.com/2009/05/cheap-ioc-in-native=
-c.html
I implemented an example of how I see IoC. This is just a naive attempt,
since the way the parameters are passed to the constructor is not very
good (at least in my opinion :) )
Can someone recommend a better way? A link to an example, or explanation
how it is done, would be best.
The first step is to get an exploitable typeid information. IIRC
Andrei Alexandrescu gives an implementation in Modern C++; it uses a
TypeInfo wrapper storing a pointer on std::type_info and defining a
strict ordering on the member "before" (which defines a global
ordering).
One you have that, you can define a map of typeinfo to a builder
pattern.
For, the way to register/recover an implementation (like in the
article, I would use a proxy object to ensure type compatibility and
type safety.
Something like:
class IoCBuilderBase
{
virtual ~IoCBuilderBase(){}
};
template<class T>
struct IoCBuilder: IoCBuilderBase
{
virtual T* build(/* parameters */) = 0;
};
struct IoC
{
static std::map<TypeInfo,IoCBuilderBase*> _builders;
template<class T>
struct Interface
{
static void registerBuilder(T* (*builder)() )
{
// allocate type inherithing IoCBuilder<IoCBuilder>
IoC::_builders[TypeInfo(typeid(T))]=ptr;
}
// other registration with fonctor ...
static T* create()
{
IoCBuilderBase* ptr = // get base with TypeInfo(typeid(T))
IoCBuilder<IoCBuilder>* builder = dynamic_cast<
IoCBuilder<IoCBuilder>* >(ptr);
assert( builder )
return builder->build();
}
};
};
That way, in you example, you write
IoC::Interface<I>::registerBuilder(&A::create);
I* i = IoC::Interface<I>::create();
assert( dynamic_cast<A*>(i) );
IoC::Interface<I>::registerBuilder(&B::create);
i = IoC::Interface<I>::create();
assert( dynamic_cast<B*>(i) );
--
Michael