1

我遇到了一个令人沮丧的编译器错误,我似乎无法解决。这与模板专业化有关,但我看不出有什么问题......

../../include/thread/lock_guard.inl:23: error: template-id 'lock_guard<>' for 'thread::lock_guard<thread::null_mutex>::lock_guard(thread::null_mutex&)' does not match any template declaration
../../include/thread/lock_guard.inl:23: error: invalid function declaration
../../include/thread/lock_guard.inl:29: error: template-id 'lock_guard<>' for 'thread::lock_guard<thread::null_mutex>::~lock_guard()' does not match any template declaration
../../include/thread/lock_guard.inl:29: error: invalid function declaration

代码如下:

 #include "thread/mutex.hpp"

namespace thread {

    template <typename T>
    class lock_guard
    {
        public:
            lock_guard(T& lock);
            ~lock_guard();

        private:
            mutable T&  m_lock;
            mutable int m_state;
    };

    template <>
    class lock_guard<null_mutex>
    {
       public:
            lock_guard(null_mutex&);
            ~lock_guard();
    };

} //namespace

#include "thread/lock_guard.inl"

------------------------------------    

#include "thread/lock_guard.hpp"

namespace thread {

    template <typename T>
    lock_guard<T>::lock_guard(T& lock)
        : m_lock(lock),
          m_state(lock.lock())
    {
        /* do nothing */
    }

    template <typename T>
    lock_guard<T>::~lock_guard()
    {
        if(0 == m_state) 
        {
            m_lock.unlock();
        }
    }

    template <>
    lock_guard<null_mutex>::lock_guard(null_mutex&)
    {
        /* do nothing */
    }

    template <>
    lock_guard<null_mutex>::~lock_guard()
    {
        /* do nothing */
    }

} //namespace
4

2 回答 2

14

完整的类模板特化不再是模板,它是一个常规类。因此,在定义其成员时不需要 template<> :

lock_guard<null_mutex>::lock_guard(null_mutex&)
{
    /* do nothing */
}

lock_guard<null_mutex>::~lock_guard()
{
    /* do nothing */
}
于 2011-01-14T18:01:09.143 回答
2

也许这不是错误的原因,但您不需要头文件中的专业化代码。

于 2011-01-14T18:07:28.733 回答