在 C++ 中通过模板参数传递类构造函数
我知道函数可以通过 template
参数传递,我可以像这样传递类构造函数吗?
更新: 我想要这样做的全部原因是我可以在内存池中选择构造函数,并且无需在我想要分配的类中更改任何代码(在本例中为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)>();
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)>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能传递构造函数,但可以传递工厂函子:
You cannot pass around constructors, but you can pass around factory functors:
你的整个假设都是错误的。你不需要那个功能。
new
之后的东西是类型,而不是构造函数引用。Your whole assumption is wrong. You don't need that feature.
The thing after
new
is a type, not a constructor reference.我认为这样更好
This way better I think