c++ - move 语义 : invalid conversion from `type&&` to `type` . 模板:将未知参数传递给重载函数

标签 c++ move-semantics variadic-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];
}

这将接受任意数量的参数,并将它们(左值复制,右值 move )转发到 T 构造函数中。然后,该临时对象将被 move 分配到 *cells[cellNo] 中。

关于c++ - move 语义 : invalid conversion from `type&&` to `type` . 模板:将未知参数传递给重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35559323/

相关文章:

c++ - 如何在 Fedora 中编译 sqlite3.c?

c++ - 我们可以使用子字符串的 const ref 吗?

c++ - 微型序列化器

C++ 为什么在我的类中添加析构函数会使我的类无法 move ?

java - Java 中的可变参数

c++ - 最大和最小数显示错误

iterator - 非破坏性地迭代 Rust 集合,但不是通过引用

c++ - 返回一个右值——这段代码有什么问题?

java - 通用可变参数的警告

更改返回的可变参数函数指针