我写过3个互斥类TMutex,TCondition和TSpinLock都有一个void lock()和一个void unlock()成员。现在我想在它们上使用std :: lock_guard。我在源文件的末尾为我的新互斥类实例化了lock_guard:
template class std::lock_guard<app::TMutex>;
template class std::lock_guard<app::TCondition>;
template class std::lock_guard<app::TSpinLock>;
如果我使用:
TCondition cond;
std::lock_guard<std::mutex> lock(cond);
我收到以下编译器错误消息:
../ src / inc / threads.cpp:317:39:错误:没有匹配函数来调用&#39; std :: lock_guard :: lock_guard(app :: TCondition&amp;)&#39; ../src/inc/threads.cpp:317:39:注意:候选人是: /usr/include/c++/4.6/mutex:447:7:注意:std :: lock_guard&lt; _Mutex&gt; :: lock_guard(std :: lock_guard&lt; _Mutex&gt; :: mutex_type&amp;,std :: adopt_lock_t)[with _Mutex = std :: mutex,std :: lock_guard&lt; _Mutex&gt; :: mutex_type = std :: mutex] /usr/include/c++/4.6/mutex:447:7:注意:候选人需要2个参数,1个提供 /usr/include/c++/4.6/mutex:444:16:注意:std :: lock_guard&lt; _Mutex&gt; :: lock_guard(std :: lock_guard&lt; _Mutex&gt; :: mutex_type&amp;)[with _Mutex = std :: mutex,std :: lock_guard&lt; _Mutex&gt; :: mutex_type = std :: mutex] /usr/include/c++/4.6/mutex:444:16:注意:来自&#39; app :: TCondition&#39;的参数1没有已知的转换。 to&#39; std :: lock_guard :: mutex_type&amp; {aka std :: mutex&amp;}&#39;
我还尝试将自己的lock_guard包装器实现为新的模板类(非常类似于原始的lock_guard:
template<typename T>
class TLockGuard
{
private:
typedef T lock_t;
lock_t& instance;
public:
TLockGuard& operator=(const TLockGuard&) = delete;
explicit TLockGuard(lock_t& F) : instance(F) { instance.lock(); }
TLockGuard(const TLockGuard&) = delete;
~TLockGuard() { instance.unlock(); }
};
并为此类进行类似的实例化:
template class TLockGuard<app::TMutex>;
template class TLockGuard<app::TCondition>;
template class TLockGuard<app::TSpinLock>;
如果我像这样使用这个模板类:
TCondition cond;
std::TLockGuard<std::mutex> lock(cond);
我得到了一个不同的错误:
../ src / inc / threads.cpp:318:39:错误:没有匹配函数来调用&#39; app :: TLockGuard :: TLockGuard(app :: TCondition&amp;)&#39; ../src/inc/threads.cpp:318:39:注意:候选人是: ../src/inc/semaphore.h:164:12:注意:app :: TLockGuard :: TLockGuard(app :: TLockGuard :: lock_t&amp;)[与T = std :: mutex,app :: TLockGuard :: lock_t = std :: mutex] ../src/inc/semaphore.h:164:12:注意:来自&#39; app :: TCondition&#39;的参数1没有已知的转换。到应用程序:: TLockGuard :: lock_t&amp; {aka std :: mutex&amp;}&#39;
有人可以帮我理解两种情况下出了什么问题吗? 我更喜欢使用标准的lock_guard,但如果我自己的包装器也可以使用它会很好。
答案 0 :(得分:2)
以下示例编译正常:
#include <thread>
#include <mutex>
struct Mutex
{
void lock() {}
void unlock() {}
};
struct Condition
{
void lock() {}
void unlock() {}
};
struct SpinLock
{
void lock() {}
void unlock() {}
};
template class std::lock_guard<Mutex>;
template class std::lock_guard<Condition>;
template class std::lock_guard<SpinLock>;
int main()
{
static Mutex mutex;
std::lock_guard<Mutex> lock(mutex);
}
你的问题在于:
TCondition cond;
std::lock_guard<std::mutex> lock(cond);
您正在创建一个期望std :: mutex的lock_guard但是您传递了TCondition。
尝试更改为:
std::lock_guard<TCondition> lock(cond);