在C++中通过模板参数传递类构造函数

xuc*_*eng 2 c++ templates constructor initializer-list

我知道函数可以通过template参数传递,我可以像这样传递类Constructor.

更新: 我想要这样做的全部原因是,我可以在内存池中选择构造函数,并且在我想要分配的类中没有任何代码更改(在本例中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)>();
Run Code Online (Sandbox Code Playgroud)

fre*_*low 5

你不能传递构造函数,但你可以传递工厂仿函数:

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));
}
Run Code Online (Sandbox Code Playgroud)