我有一个并发队列的模板化实现,它具有如下所示的推送功能:
template <typename T>
class concurrent_queue
{
public:
// other code...
void push(const T& item)
{
std::unique_lock<std::mutex> mlock(mutex);
queue.push_back(std::forward(item));
mlock.unlock();
notEmpty.notify_one();
}
private:
std::deque<T> queue;
std::mutex mutex;
// other stuff...
};
稍后,我实例化它并像这样使用它:
concurrent_queue<c2Type> m_queue; // c2 type is some struct declared previously
然后我尝试将项目推送到队列中,但出现了上述编译器错误:
c2Type c2message;
// fill in the message struct...
m_queue.push(c2message);
我之前成功地将队列用作线程池实现的一部分,它存储了 std::function
对象。我不明白为什么在这种情况下它不能推断出类型。有什么想法吗?
最佳答案
“左值”和“右值”等值类别是表达式的属性。命名变量的表达式始终是左值表达式,即使它们命名一个类型为 rvalue reference to some_type
的变量也是如此。 .
我们使用左值引用和右值引用来绑定(bind)不同类别的表达式:按照惯例,我们将左值引用视为绑定(bind)到左值,将右值引用视为绑定(bind)右值。
std::forward
旨在恢复我们假设引用所指的值类别。例如:
int i = 42;
int& l = i;
int&& r = 21;
l // this expression is an lvalue-expression
r // this expression is an lvalue-expression, too (!)
std::forward<int& >(l) // this function-call expression is an lvalue-expression
std::forward<int&&>(r) // this function-call expression is an rvalue-expression
std::forward
,作为“普通函数”,不能仅通过参数来恢复值类别。两个参数都是左值表达式。您必须通过手动提供模板参数来指定要恢复的值类别。
只有当我们有一个我们先验不知道它是右值引用还是左值引用的引用时,这才有意义。当编写一个使用完美转发和转发引用的函数时就是这种情况。
顺便说一下,我们要恢复值类别以允许另一个函数从我们收到的参数中移动。如果我们收到一个右值参数,我们想传递一个右值,以允许被调用的函数移动。
对于类似于 OP 中的函数:
void push(const T& item)
我们知道item
具有对 const T
的 左值引用类型。因此,我们不需要 std::forward
:
void push(const T& item) {
// ...
queue.push_back(item); // pass the lvalue argument as an lvalue
// ...
}
如果我们添加另一个重载:
void push(T&& item)
我们仍然不需要std::forward
,因为该参数的类型 item
总是 对 T
的右值引用 (假设 T
不是引用类型):
void push(T&& item) {
// ...
queue.push_back(std::move(item)); // pass the rvalue argument as an rvalue
// ...
}
只有当我们有类似的东西时
template<typename U>
void push(forwarding_reference<U> item)
哪里forwarding_reference<U>
可以是左值引用或右值引用,那么我们需要std::forward
:
template<typename U>
void push(forwarding_reference<U> item) // not C++, read on
{
// ...
queue.push_back(std::forward<U>(item)); // pass lvalue arguments as lvalues
// and rvalue arguments as rvalues
// ...
}
由于实现细节,我们必须将上面的代码写成:
template<typename U>
void push(U&& item) {
// ...
queue.push_back(std::forward<U>(item)); // pass lvalue arguments as lvalues
// and rvalue arguments as rvalues
// ...
}
注意上面的U&& item
不是右值引用,而是转发引用。要获得转发引用,您需要有一个带有某些模板类型参数的函数模板 X
和 X&& x
形式的函数参数.
关于c++ - 错误 C2783 : '_Ty &&std::forward(remove_reference<_Ty>::type &&) throw()' : could not deduce template argument for '_Ty' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27696442/