domlao
domlao

Reputation: 16029

C++ template class that creates instances of other classes

I'm new to C++ and I don't know about template class but I think I can use template for my problem. I have two classes,

class Foo
{
 public:
    Foo (int a, char b);
};

class Bar
{
 public:
    Bar (int a);
};

And these classes are not related to each other.

My question is, is it possible to create a template class to create instances of Foo and Bar? Something that could be used like this:

TemplateClass<Foo>::createClass();

But I'm not sure about the parameter.

Upvotes: 0

Views: 198

Answers (2)

pmr
pmr

Reputation: 59811

Constructors are not normal functions and thus cannot be used with bind or other functional mechanisms easily. Writing a wrapper with limited functionality is easy with C++11 as ForEver shows, but this can become tricky without C++11 and when you need more than basic functionality. You can use Boost.Factory for that.

Upvotes: 2

ForEveR
ForEveR

Reputation: 55887

You can use C++11 for this.

template<typename T>
class TemplateClass
{
public:
   template<class... Args>
   static T createClass(Args&&... args)
   {
      return T(std::forward<Args>(args)...);
   }
};

Foo f = TemplateClass<Foo>::createClass(1, '1');
Bar b = TemplateClass<Bar>::createClass(1);

Or with C++03 use different overloads.

template<typename T>
class TemplateClass
{
public:
   static T createClass()
   {
      return T();
   }
   template<typename Arg1>
   static T createClass(const Arg1& arg)
   {
      return T(arg);
   }
   template<typename Arg1, typename Arg2>
   static T createClass(const Arg1& arg1, const Arg2& arg2)
   {
      return T(arg1, arg2);
   }
};

And so on...

Upvotes: 4

Related Questions