Object factories

D

Dave

Please see the comment in the code below. Thanks!


#include <iostream>

using namespace std;

template<typename T>
class ObjectFactory
{
public:
// For 0-argument constructors
static T *Create()
{
return new T();
}

// For 1-argument constructors
template<typename T1>
static T *Create(const T1 &arg1)
{
return new T(arg1);
}

// For 2-argument constructors
template<typename T1, typename T2>
static T *Create(const T1 &arg1, const T2 &arg2)
{
return new T(arg1, arg2);
}

// For 3-argument constructors
template<typename T1, typename T2, typename T3>
static T *Create(const T1 &arg1, const T2 &arg2, const T3 &arg3)
{
return new T(arg1, arg2, arg3);
}

// ... and so on up to N-argument constructors
};

class Foo: public ObjectFactory<Foo>
{
public:

Foo(): m_a(0), m_b(0) {}
Foo(int a): m_a(a), m_b(0) {}
Foo(int a, int b): m_a(a), m_b(b) {}

virtual ~Foo() {}

virtual void Print()
{
cout << "m_a: " << m_a << endl;
cout << "m_b: " << m_b << endl;
}

private:
int m_a;
int m_b;
};

class Goo: public Foo, public ObjectFactory<Goo>
{
public:
Goo(): m_c(0) {}
Goo(int a): Foo(a), m_c(0) {}
Goo(int a, int b): Foo(a, b), m_c(0) {}
Goo(int a, int b, int c): Foo(a, b), m_c(c) {}

virtual ~Goo() {}

virtual void Print()
{
Foo::print();
cout << "m_c: " << m_c << endl;
}

private:
int m_c;
};

int main()
{
Foo *Ptr_1 = Foo::Create(1, 2); // No problem
Ptr_1->Print();

// Goo:: Create() is ambiguous. How may I have it resolve to the
// ObjectFactory directly inherited by Goo?
Foo *Ptr_2 = Goo::Create(17, 42, 243);
Ptr_2->Print();

return 0;
}
 
V

Victor Bazarov

Dave said:
Please see the comment in the code below. Thanks!

[...]
class Goo: public Foo, public ObjectFactory<Goo>
{
public:
Goo(): m_c(0) {}
Goo(int a): Foo(a), m_c(0) {}
Goo(int a, int b): Foo(a, b), m_c(0) {}
Goo(int a, int b, int c): Foo(a, b), m_c(c) {}

virtual ~Goo() {}

virtual void Print()
{
Foo::print();
cout << "m_c: " << m_c << endl;
}

Try adding

using ObjectFactory said:
private:
int m_c;
};

int main()
{
Foo *Ptr_1 = Foo::Create(1, 2); // No problem
Ptr_1->Print();

// Goo:: Create() is ambiguous. How may I have it resolve to the
// ObjectFactory directly inherited by Goo?
Foo *Ptr_2 = Goo::Create(17, 42, 243);
Ptr_2->Print();

return 0;
}

See above.

Victor
 
M

Mike Wahler

Dave said:
int main()
{
Foo *Ptr_1 = Foo::Create(1, 2); // No problem
Ptr_1->Print();

// Goo:: Create() is ambiguous. How may I have it resolve to the
// ObjectFactory directly inherited by Goo?

Hint: 'using' (it's not just for namespaces :) )

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top