模板类工厂

时间:2016-09-30 12:59:46

标签: c++ plugins factory

我不确定如何在c ++中实现这一点,但是当我从他们的插件中请求利用我的核心库的某种对象时,我想阻止我的库用户提供单例对象。我尝试了很多变种,但这是我目前在C ++模板工厂实现的尝试。

问题作为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
}

//===========================================================================

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助:

template <typename T> 
class FooProvider : public IFooProvider
{
    static_assert( std::is_convertible< T*, IFoo* >::value,
                   "Interface needs to be of type IFoo" );

    std::shared_ptr<IFoo> getProvidedFoo()
    {
        std::shared_ptr<IFoo> rtn = 
             static_pointer_cast<IFoo> ( std::make_shared<T>() );
        return rtn;
    }
}

答案 1 :(得分:0)

如果你想要编译时间:

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,您将收到一个编译时错误,说它无法转换“#”;&#39;&#39;从std :: shared_ptr到std :: shared_ptr - 一个非常明显的错误信息。