简体   繁体   English

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

[英]Pass class Constructor through template argument in C++

I know function can pass through template argument, can I pass class Constructor like this. 我知道函数可以通过template参数,我可以像这样传递类Constructor。

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

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. new之后的东西是一个类型,而不是构造函数引用。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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