【发布时间】:2014-12-29 21:38:56
【问题描述】:
我有一个并发队列的模板化实现,它具有如下所示的推送功能:
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 对象。我不明白为什么在这种情况下它不能推断出类型。有什么想法吗?
【问题讨论】:
-
queue.push_back(std::forward(item));没有理由转发 对常量T的引用。 -- 错误的原因是您必须手动为std::forward提供模板参数:std::forward<T>(t),因为它(旨在)“恢复”t的值类别,如果t是转发参考。 -
谢谢。我删除了 const 并添加了模板参数,它解决了问题。如果您将评论添加为答案,我会接受。
-
我认为您应该使用
void push(T&& item),不使用const并作为通用参考(&&)。并使用明确的T调用forward<T>。如果您想保留 const,您还应该将其添加到对forward<const T>的调用中。请参阅isocpp.org/blog/2012/11/… 了解有关不同类型引用的混乱的更多详细信息。
标签: c++ c++11 perfect-forwarding forwarding-reference