mardi 30 juin 2015

How to use another class as a class template specialization

I have a hybrid-lock class that spin tries a lock for a (compile time fixed) number of spins before falling back to blocking on a std::mutex until the lock becomes available.

Simplified:

#include <mutex>

template<unsigned SPIN_LIMIT>
class hybrid_lock {
public:
    void lock(){
        for(unsigned i(0);i<SPIN_LIMIT;++i){
            if(this->mMutex.try_lock()){
                return;        
            }
        } 
        this->mMutex.lock();
    }
    void unlock(){
        this->mMutex.unlock();
    }
private:
    std::mutex mMutex;
};

In the special case of SPIN_LIMIT==0 this falls back to being a 'plain' std::mutex (i.e. no visible spins).

So I've specialized that to:

template<>
class hybrid_lock<0> : public std::mutex {};

It works fine but is that the approved way of specializing class templates to be another (pre-existing) template?

Aucun commentaire:

Enregistrer un commentaire