简体   繁体   中英

Pass class Constructor through template argument in C++

I know function can pass through template argument, can I pass class Constructor like this.

Update: The whole reason that I want to do this, is I can choose constructor in memory pool and without any code changing in the class I want to alloc (in this case class A )

class A
{
public:
  A(){n=0;}
  explicit A(int i){n=i;}

private:
  int n;
};

class MemoryPool
{
public:
   void* normalMalloc(size_t size);
   template<class T,class Constructor>
   T* classMalloc();
};

template<class T,class Constructor>
T* MemoryPool::classMalloc()
{
   T* p = (T*)normalMalloc(sizeof(T));
   new (p) Constructor; // choose constructor
   return p;
}

MemoryPool pool;
pool.classMalloc<A,A()>(); //get default class
pool.classMalloc<A,A(1)>();

You cannot pass around constructors, but you can pass around factory functors:

class A
{
    int n;

    A(int i) : n(i) {};

public:

    static A* makeA(int i)
    {
        return new A(i);
    }
};

template<typename T, typename Factory>
T* new_func(Factory factory)
{
    return factory();
}

#include <functional>

int main()
{
    new_func<A>(std::bind(&A::makeA, 0));
    new_func<A>(std::bind(&A::makeA, 1));
}

Your whole assumption is wrong. You don't need that feature.

template<class T>
T* new_func()
{
   return new T;
}

The thing after new is a type, not a constructor reference.

This way better I think

template<class T, int n>
struct Factory
{
  static T* new_func()
  {
     return new T(n);
  }
};

template<class T>
struct Factory<T,0>
{
  static T* new_func()
  {
     return new T;
  }
};

T* t = Factory<T>::new_func(); //call default constructor
T* t2 = Factory<T,2>::new_func(); //call constructor T(2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM