【发布时间】:2018-07-20 16:52:01
【问题描述】:
我希望能够创建一个 T 类型的新对象,如这段代码 sn-p 所示。
template<typename T, typename Arg1, typename Arg2>
void ManageDevice(T& device, Arg1 arg1, Arg2 arg2)
{
auto newDevice = new T{ arg1, arg2 };
// ... Perform more operations on newDevice
}
我目前正在使用这样的功能:
CertainClass* device;
ManageDevice(device, arg1, arg2);
编译器返回错误:Cannot convert from "initializer list" to "class of T*"。
我也试过了:
auto newDevice = new decltype(device){ arg1, arg2 };
并得到以下错误:
错误 C2464 'class of T*&': 不能使用 'new' 来分配引用
所以我删除了这个引用:
using DeviceType = std::remove_reference<decltype(device)>::type;
auto newDevice = new DeviceType{ arg1, arg2 };
我又收到了第一条错误消息。
问题:
- 知道这是否合法,我该怎么做才能让它发挥作用?
- 在理想情况下,我希望通过直接传递指向类的指针而不是此类的实例来调用函数,这可能吗?
- 这叫什么名字?
【问题讨论】:
-
这看起来像是您想要使用完美转发的情况。 stackoverflow.com/questions/24732926/…
标签: c++ class templates memory new-operator