我寫了3個互斥類TMutex,TCondition和TSpinLock都有一個void lock()和一個void unlock()成員。現在我想對他們使用std :: lock_guard。我instatiate在我的源文件的末尾lock_guard爲我的新的mutex類是這樣的:使用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: error: no matching function for call to 'std::lock_guard::lock_guard(app::TCondition&)' ../src/inc/threads.cpp:317:39: note: candidates are: /usr/include/c++/4.6/mutex:447:7: note: std::lock_guard<_Mutex>::lock_guard(std::lock_guard<_Mutex>::mutex_type&, std::adopt_lock_t) [with _Mutex = std::mutex, std::lock_guard<_Mutex>::mutex_type = std::mutex] /usr/include/c++/4.6/mutex:447:7: note: candidate expects 2 arguments, 1 provided /usr/include/c++/4.6/mutex:444:16: note: std::lock_guard<_Mutex>::lock_guard(std::lock_guard<_Mutex>::mutex_type&) [with _Mutex = std::mutex, std::lock_guard<_Mutex>::mutex_type = std::mutex] /usr/include/c++/4.6/mutex:444:16: note: no known conversion for argument 1 from 'app::TCondition' to 'std::lock_guard::mutex_type& {aka std::mutex&}'
我還嘗試將自己的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(); }
};
,並做similiar實例化這個類:
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: error: no matching function for call to 'app::TLockGuard::TLockGuard(app::TCondition&)' ../src/inc/threads.cpp:318:39: note: candidate is: ../src/inc/semaphore.h:164:12: note: app::TLockGuard::TLockGuard(app::TLockGuard::lock_t&) [with T = std::mutex, app::TLockGuard::lock_t = std::mutex] ../src/inc/semaphore.h:164:12: note: no known conversion for argument 1 from 'app::TCondition' to 'app::TLockGuard::lock_t& {aka std::mutex&}'
有人能幫助我理解在這兩種情況下出了什麼問題嗎? 我寧願使用標準的lock_guard,但如果我自己的包裝也可以工作,它會很好。
'的std :: lock_guard鎖(條件);' –
dyp
2014-10-06 18:09:31
@dyp後,作爲一個答案 – inf 2014-10-06 18:10:17
*「我instatiate在我的源文件的末尾爲我的新lock_guard像這樣的互斥類「*我不確定你想通過顯式實例化來實現什麼。 – dyp 2014-10-06 18:12:45