模板类工厂 [英] factory of templated class
问题描述
我不确定如何在c ++中完成此操作,但是当我从他们的插件中请求某种利用我的核心库的对象来请求某种对象时,我想阻止我的库用户提供单例对象.我已经尝试了很多变体,但这是我目前在C ++的模板化工厂中实现的尝试.
I'm not sure how to accomplish this in c++, but I want to prevent users of my library from providing singleton objects when I request a certain kind of object from their plugin that leverages my core libraries. I've tried a bunch of variations, but this is my current attempt at an implementation at a templated factory in C++.
问题作为注释嵌入在FooProvider.h存根中.谢谢!
Questions are embedded as comments in FooProvider.h stub. Thanks!
/*
* 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
}
//===========================================================================
推荐答案
如果要捕获编译时间:
template <typename T>
class FooProvider : public IFooProvider
{
std::shared_ptr<IFoo> getProvidedFoo()
{
std::shared_ptr<T> rtn = std::make_shared<T>();
return rtn;
}
}
不需要强制转换,如果T不扩展IFoo,您将收到一个编译时错误,提示它无法将'rtn'从std :: shared_ptr转换为std :: shared_ptr-这是一个非常明显的错误消息.
No casting needed, and if T doesn't extend IFoo you'll get a compile time error saying that it couldn't convert 'rtn' from std::shared_ptr to std::shared_ptr - a pretty obvious error message.
这篇关于模板类工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!