C ++在运行时选择一个随机对象

时间:2018-07-02 15:34:58

标签: c++

我想选择一个随机类,并在运行时创建一个对象(我选择的类是从基类派生的)。我该怎么做

1 个答案:

答案 0 :(得分:2)

使用工厂函数:每个类都应提供具有相同签名的静态函数,该函数将返回指向基类的指针。然后,构建具有相同签名的那些工厂函数的数组,以便您可以随机选择。

#include <memory>
#include <vector>
#include <random>

class CommonClass
{
public:
    typedef std::shared_ptr<CommonClass> (*FactoryFunction)(); // type for factory function
};

class A : public CommonClass
{
public:
    A() {};
    static std::shared_ptr<CommonClass> Create() { return std::make_shared<A>(); }
};

class B : public CommonClass
{
public:
    B() {};
    static std::shared_ptr<CommonClass> Create() { return std::make_shared<B>(); }
};


std::shared_ptr<CommonClass> CreateRandom()
{
    // Vector of factory functions, initialized once.
    static std::vector< CommonClass::FactoryFunction >  factories = 
        { &A::Create, &B::Create };

    std::random_device rd;
    std::uniform_int_distribution<> dis(0, 1);

    // Generate random index, look up factory function, then call it
    return factories[dis(rd)]();
}

int main()
{
    std::shared_ptr<CommonClass> c(CreateRandom());
}

评论者提出了一个很好的观点。这是使用CRTP一次编写工厂函数的顶部的替代版本:

// Interface layer
class CommonClass
{
public:
    typedef std::shared_ptr<CommonClass> (*FactoryFunction)();
};

// CRTP layer.  Put any subclass implementation here that can be expressed
// as a compile-time expression of the type of the subclass.
template<class S>
class CommonClassImpl : public CommonClass
{
public:
    static std::shared_ptr<CommonClass> Create() { return std::make_shared<S>(); }
};


class A : public CommonClassImpl<A>
{
public:
    A() {};
};


class B : public CommonClassImpl<B>
{
public:
    B() {};
};