开发者

Can I pass a constructor to a function?

I want to instantiate a base class pointer to point to a newly constructed derived class object. The actual class for the object will change depending on the application type, so I want to use a Factory method to switch on certain variables in order to construct the right object.

However I don't want to have to do the switch each time. In fact, once the application starts, the type of object I want to create in this situation will always be the same - so actually I only need to do this switch only once.

Can I pass in a derived class Constructor to the function creating the object?

For example:

typedef DerivedObject (*DerivedClassConstructor)( void );
class ContainingClass:
{
public:
    ContainingClass ( DerivedClassConstructor * f ) 
    {
       baseptr = f();
    }

    BaseClass * baseptr
};

Is th开发者_开发百科ere a better design?


Would it not be easier to templatise the code.
That way it looks like normal code.

class BaseClass
{};
class Derived: public BaseClass
{};

template<typename T>
class ContainingClass
{
    public:
        ContainingClass()
        {
            baseptr = new T();
        }

        BaseClass * baseptr;
};

int main()
{
     ContainingClass<Derived>  cont;
}


I think that's pretty sane. Just pass a function object and save it since it seems you need to recall it later (otherwise why not pass the pointer directly and create the object before?)

class ContainingClass:
{
public:
    typedef boost::function<BaseClass*()> factory_fn;

public:
    ContainingClass (factory_fn f ) 
      :m_f(f)
    {
       baseptr = m_f();
    }

    BaseClass * baseptr
    factory_fn m_f;
};


template<typename T>
struct DerivedFactory {
    BaseClass *operator()() {
        return new T;
    }
};


ContainingClass c((DerivedFactory<DerivedClass>()));


You can't do it with a constructor, since a constructor is not actually returning a class instance.

You talk about a factory method, and you got half way towards actually using one. However, it is not a good idea to create a dependency from base class to derived class - why can't your factory method simply return (a pointer to) BaseClass objects?

typedef BaseClass* (*BaseClassFactory)( void );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜