簡體   English   中英

在C ++中通過模板參數傳遞類構造函數

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

我知道函數可以通過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)>();

你不能傳遞構造函數,但你可以傳遞工廠仿函數:

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));
}

你的整個假設是錯誤的。 您不需要該功能。

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

new之后的東西是一個類型,而不是構造函數引用。

這種方式我覺得更好

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