移动语义:从"类型&&"到"类型"的转换无效。模板:将未知参数传递给重载函数
Move semantics: invalid conversion from `type&&` to `type`. Templates: passing unknown arguments to overloaded functions
故事如下:有一个固定类型的内存池Pool
,用于存储某种类型T
的元素。标题中列出的两个问题都是在制作构造新元素并将其添加到池中的alloc()
函数时遇到的:
template <class T, size_t qty, class Alloc = allocator<T>>
class Pool {
array <T*, qty> cells; // Pointers to pre-allocated memory
...
public:
T& alloc (...) { // [2] It is unknown what parameters T's constructor may take
T&& tmp (...); // [2] But I need them to be passed as they are
size_t cellNo = findEmptyCell(); // Returns the number of the cell
*cells[cellNo] = tmp; // Placing the new object into the pool
// [1] "invalid conversion from 'int&& (*)(...)' to 'int'" when T is int
isEmpty[cellNo] = false; // Marking the cell as occupied
return *cells[cellNo];
}
}
那么,1)在这种情况下如何避免不必要的对象复制?
2)有没有办法将任意参数传递给构造函数?
您正在寻找带有可变参数函数模板的"完美转发":
template <class... Args>
T& alloc(Args&&... args) {
size_t cellNo = findEmptyCell();
*cells[cellNo] = T(std::forward<Args>(args)...);
isEmpty[cellNo] = false;
return *cells[cellNo];
}
这将接受任意数量的参数,并将它们转发(复制为右值,移动为右值)到T
构造函数中。然后,该临时对象将被移动到*cells[cellNo]
中。
相关文章:
- OpenCV C++:当垫子类型未知时无法访问垫子元素?
- 参数数据类型未知的可变参数函数
- 矢量迭代器类型未知
- 模板函数的返回类型未知,使用 decltype 时代码重复
- 使用不同类型 /未知类型的类模板初始化向量
- 当类型未知时调用模板方法
- 当类类型未知时,指向非静态成员函数的函数指针
- 如何在数据类型未知的C++中创建模板类
- 组件 X 的超类型未知,其某些属性未经验证
- 当数据类型未知时如何声明数组
- 如何在对象类型未知时实现交换函数
- 类成员是类型未知的派生对象
- 模板中的返回类型未知
- 在运行时之前调用类型未知的模板化函数
- 当类类型未知时调用成员函数
- 在编译时使用类型未知的对象初始化
- 处理运行时类型未知的模板
- 模板类的返回类型未知
- 当编译时数据格式和类型未知时,C++将数据读入内存
- 属性类型未知的模板类中的默认构造函数