C++11实现可变参数模板类封装
程序员文章站
2024-03-14 11:06:04
...
#include <memory.h>
/// <summary>
/// 对象池中的对象的模板类
/// </summary>
template<class T>
class CObjInstance
{
public:
/// <summary>
/// 重载new操作符
/// </summary>
/// <param name="nSize">分配内存大小</param>
/// <returns></returns>
void* operator new (size_t nSize)
{
return std::malloc(nSize);
}
/// <summary>
/// 重载delete操作符
/// </summary>
/// <param name="p"></param>
void operator delete (void* p)
{
std::free(p);
}
/// <summary>
/// 创建对象
/// </summary>
/// <param name="...args">可变参数</param>
/// <returns></returns>
template<typename ...Args>//可变参数
static T* CreateObj(Args ... args)
{
T* obj = new T(args...);
return obj;
}
static void DeleteObj(T* obj)
{
delete obj;
}
};
测试代码:
#include "CObjInstance.h"
class A: public CObjInstance<A>
{
public:
A(int n)
{
a = n;
}
~A()
{
std::cout << "~A" << std::endl;
}
public:
int a = 0;
};
class B: public CObjInstance<B>
{
public:
B(int n, int m)
{
a = n;
b = m;
}
~B()
{
std::cout << "~B" << std::endl;
}
public:
int a = 0;
int b = 0;
};
void Test()
{
A* a = A::CreateObj(3);
std::cout << a->a << std::endl;
A::DeleteObj(a);
B* b = B::CreateObj(6, 9);
std::cout << b->a << b->b << std::endl;
B::DeleteObj(b);
}
int main()
{
Test();
std::cout << "Hello World!\n";
}
实现结果:
推荐阅读