From:
http://sourceforge.net/forum/forum.php?thread_id=1076322&forum_id=93008
The Factory component in Loki is really useful but it
returns plain old C++ pointers, which I don't use
anymore (my current favourite is boost::shared_ptr).
I think Factory could be altered to be more generic
by using a "return type" trait class.
Consider the following:
template <typename T>
class PointerReturnTraits
{
public:
typedef T* ReturnType;
ReturnType OnUnknownTypeConv(T* rt)
{
return rt;
}
};
template <typename T>
class SharedPtrReturnTraits
{
public:
typedef boost::shared_ptr<T> ReturnType;
ReturnType OnUnknownTypeConv(T* rt)
{
return ReturnType(rt);
}
};
template
<
class AbstractProduct,
typename IdentifierType = int,
template <typename> ReturnTraits =
SharedPtrReturnTraits,
typename ProductCreator = typename
ReturnTraits<AbstractProduct>::
ReturnType (*)(),
template<typename, class>
class FactoryErrorPolicy = DefaultFactoryError
>
typename ReturnTraits<AbstractProduct>::ReturnType
CreateObject(
const IdentifierType& id)
{
typename IdToProductMap::iterator i =
associations_.find(id);
if (i != associations_.end())
{
return (i->second)();
}
return ReturnTraits<AbstractProduct>().
OnUnknownTypeConv(OnUnknownType(id));
}
I've had similar code working under Dev C++ and
C++ Builder (had to change the template template
parameter ReturnTraits to an ordinary parameter
because of what looks like a bug in Borland).
Regards, Brian
Logged In: YES
user_id=1882902
Originator: NO
In my use case, the return type would be a boost::variant (a discriminated union container). I also think that the concept of AbstractProduct and the factory return type should be generalized some way. Actually couldn't they be the same ? Is it to much to ask the user to write Factory<AbstractProduct*, ...> if he want to use the way it works nowdays ?
I would be OK with the proposed return traits and it is probably a better solution for backward compatibility since this new template parameter could have a default value.
Regards, Samuel