【发布时间】:2016-09-30 12:59:46
【问题描述】:
我不确定如何在 c++ 中完成此操作,但我想阻止我的库的用户在我从他们的插件请求某种利用我的核心库的对象时提供单例对象。我尝试了很多变体,但这是我目前在 C++ 模板工厂中实现的尝试。
问题作为 cmets 嵌入 FooProvider.h 存根中。谢谢!
/*
* IFooProvider.h
*/
//Interface - Factory for different variations of IFoo
class IFooProvider
{
virtual std::shared_ptr<IFoo> getProvidedFoo();
}
//===========================================================================
/*
* FooProvider.h
*/
template <typename T> //Not sure how to enforce that T is derived from IFoo?
class FooProvider : public IFooProvider
{
std::shared_ptr<IFoo> getProvidedFoo()
{
//This doesn't work.
//Not sure how to perform this cast or if this is even possible?
std::shared_ptr<IFoo> rtn = std::make_shared<T>();
return rtn;
}
}
//===========================================================================
//Other team's implementation version. Exists in a different library that I have no control over.
/*
* MyFooProvider.h
*/
class MyFooProvider : public FooProvider<MyFoo>
{
//Nothing really going on here. Just want to implement a provider for MyFoo
}
//===========================================================================
【问题讨论】:
-
要么使用工厂方法设计,要么使用模板类进行设计,但不能同时使用两者。工厂方法应该允许您通过提供最少的参数来创建继承和注册的对象。
-
您的代码(添加了缺少的代码)works 非常好。