gpt4 book ai didi

c++ - 将构造函数参数传递给模板函数工厂

转载 作者:太空狗 更新时间:2023-10-29 20:27:10 26 4
gpt4 key购买 nike

我有这个功能:

template <class T> 
T *allocate()
{
T *obj = new(top) T();
top += sizeof(T);
return obj;
}

现在,使用默认构造函数创建对象效果很好,但是如何创建需要传递新参数的对象?

我知道它可以使用 C++11 的可变参数 template 来实现,但是如果没有 C++11 功能我怎么能做到这一点呢? (显然我的 VS2012 版本还不支持此功能,但我想知道如何在没有此功能的情况下执行此操作,即使升级会修复它)

最佳答案

没有一种语言功能可以取代可变参数模板(当然,否则它们就不会被发明出来)。

您可以提供多个重载,最多接受 N参数(为了合理选择 N )。每个重载都会将其参数完美转发给 T 的构造函数.

所以除了你的空函数模板:

template <class T>
T *allocate()
{
T *obj = new(top) T();
top += sizeof(T);
return obj;
}

您将拥有一个一元函数模板:

template <class T, class P1>
T *allocate(P1&& p1)
{
T *obj = new(top) T(std::forward<P1>(p1));
top += sizeof(T);
return obj;
}

二元函数模板:

template <class T, class P1, class P2>
T *allocate(P1&& p1, P2&& p2)
{
T *obj = new(top) T(std::forward<P1>(p1), std::forward<P2>(p2));
top += sizeof(T);
return obj;
}

三元函数模板:

template <class T, class P1, class P2, class P3>
T *allocate(P1&& p1, P2&& p2, P3&& p3)
{
T *obj = new(top) T(std::forward<P1>(p1), std::forward<P2>(p2),
std::forward<P3>(p3));
top += sizeof(T);
return obj;
}

等等(你明白了)。如果您介意代码复制,您可以找出一些可以减轻痛苦的宏 - 但它们并不能消除它,尤其是在您不喜欢宏的情况下。

不要忘记:

#include <utility>

访问 std::forward<>() .

关于c++ - 将构造函数参数传递给模板函数工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17090796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com